我正在尝试用 C# 从 list<string>
中编写一个 .csv 文件大约有 350 行(13 列)。
我用循环写入文件,但只有一部分列表写入文件(206 行半)。
这是我的代码:
StreamWriter file = new StreamWriter(@"C:\test.csv", true);
foreach (string s in MyListString)
{
Console.WriteLine(s); // Display all the data
file.WriteLine(s); // Write only a part of it
}
为什么我的文件没有正确填写?是否有任何限制需要考虑?
最佳答案
看起来您可能需要Flush
或Close
编写器。此外,大多数时候您可能希望将编写器包装在 using
语句中。
幸运的是,在处理时它会自动关闭编写器,刷新要写入的最后一批项目,因此它也解决了您的问题以及处理您现在已完成的任何非托管项目。
尝试以下操作:
using (StreamWriter file = new StreamWriter(@"C:\test.csv", true))
{
foreach (string s in MyListString)
{
Console.WriteLine(s); // Display all the data
file.WriteLine(s); // Write only a part of it
}
}
关于c# - 为什么我的 List<string> 没有完全写在我的 .CSV 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17523430/