为什么我的List <string>不能完全写在我的.CSV中?</string>

时间:2013-07-08 09:39:37

标签: c# csv streamwriter

我正在尝试用list<string>编写一个带有大约350行(13列)的C#中的.csv文件。 我在文件中写了一个循环,但只有我的列表的一部分写在文件中(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
        }

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

3 个答案:

答案 0 :(得分:5)

您可能需要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
    }
}

答案 1 :(得分:2)

您必须关闭您的信息流:

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
    }
}

答案 2 :(得分:0)

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

    }
}
相关问题