c# - 为什么我的 List<string> 没有完全写在我的 .CSV 中?

标签 c# csv streamwriter

我正在尝试用 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
        }

为什么我的文件没有正确填写?是否有任何限制需要考虑?

最佳答案

看起来您可能需要FlushClose 编写器。此外,大多数时候您可能希望将编写器包装在 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/

相关文章:

linux - 在 CSV 文件末尾添加空列

c# - LINQ C# 查询的逻辑是什么?

c# - EntityFramework EntityCollection 观察 CollectionChanged

python - 如何创建包含空 csv 字段为 None 的字典?

C# 单元测试 StreamWriter 参数

c# - 在 C# 中创建文本文件

c# - 字典排序

c# - ASP.NET 模板

c# - C# 中的多维列表

r - 如何从 R 中的数据框中去除美元符号 ($)?