我正在尝试从一个csv文件中读取信息并将其写入另一个文件。当我运行程序时,只有最后一行被写入新文件
while ((txtline = sr.ReadLine()) != null) // Reads one line into the variable txtline
{
//spiliting the file into columns if there is something in it.
oldcolumns = txtline.Split(',');
//oldcolumns = Regex.Split(txtline,",");
//writing the oldcolumns data into the newcolumns.
newcolumns[0] = oldcolumns[1];
newcolumns[1] = oldcolumns[0];
newcolumns[2] = "";
newcolumns[3] = oldcolumns[3];
newcolumns[4] = oldcolumns[4];
newcolumns[5] = "";
newcolumns[6] = "";
//using loop to run through all the columns
csvline = "";
for (int i = 0; i < 7; i++)
{
csvline = csvline + "\"" + newcolumns[i].Replace("\"","") + "\",";
}
}
//writing to file.
sw.WriteLine(csvline);
答案 0 :(得分:3)
在sw.WriteLine(csvline)
循环内移动while
:
while ((txtline = sr.ReadLine()) != null)
{
...
sw.WriteLine(csvline);
}
// currently its here, so it prints only last line after you exit loop