Error when converting a csv file to html using c#
I am trying to convert a csv file to html by using stream reader and writing that into stream writer. The problem is it is missing the last line of the csv file. I debugged and tried tracing the stream reader but I am unable see stream reader output in the watch at each loop.
string Line, path = @"C:\Vertex\nov\Source\Reports\Rpt_Disconn_and_Reconn_List_for_Customer_Operations_Results.csv";
System.IO.StreamReader ObjectStreamReader = null;
System.IO.StreamWriter ObjectStreamWriter = null;
ObjectStreamReader = new System.IO.StreamReader(path);
ObjectStreamWriter = new System.IO.StreamWriter("result.html");
Line = ObjectStreamReader.ReadLine();
ObjectStreamWriter.Write("<html><head><table border =1><>");
ObjectStream.Writer.Write(""):
while (ObjectStreamReader.Peek() > -1)
{
Line = ObjectStreamReader.ReadLine();
ObjectStreamWriter.WriteLine("<tr><td>" +
开发者_JAVA技巧 string.Join("</td><td>", Line.Split('\t')) +
"</td></tr>");
}
ObjectStreamWriter.WriteLine("</table></body></html>");
I would suggest using the File.ReadAllLines in something like this:
const string path = @"c:\temp\data.csv";
const char token = '\t';
string[] lines = File.ReadAllLines(path);
StringBuilder result = new StringBuilder();
result.Append("<html><head><table border =1>");
foreach (string line in lines)
{
string[] parts = line.Split(token);
string row = "<tr><td>" + string.Join("</td><td>", parts) + "</td></tr>";
result.Append(row);
}
result.Append("</table></body></html>");
精彩评论