尝试将列表项写入文本文件,但文件最终空白

时间:2019-02-25 18:13:24

标签: c# arraylist filestream

我有一个类TestLogEntry,其ToString()方法已被重写,如下所示:

   class TestLogEntry
    {
        public int counter;
        public string filename;
        public long id;
        public int featureCount_existing;
        public string fromPath;
        public int featureCount;
        public bool isCheckedOut;
        public bool modifiedByThisUser;
        public bool canUpdate;

        public string ToString()
        {
            return String.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8}", counter, filename, id, featureCount_existing, fromPath, featureCount, isCheckedOut, modifiedByThisUser, canUpdate);
        }
    }

我有一个List<TestLogEntry>实例testLog,我正在尝试将其读入文本文件:

    using (FileStream fs = File.Open(@"C:\Logs\TestLog\testLog.csv",FileMode.Create))
    {
        StreamWriter sw = new StreamWriter(fs);
        testLog.ForEach(r => sw.WriteLine(r.ToString()));
    }
当我在testLog语句的断点处检查

ForEach时,显然其中有数据,但此操作完成后,该文件为空白。如何将列表内容写入文件?

2 个答案:

答案 0 :(得分:1)

添加sw.Close()

    using (FileStream fs = File.Open(@"C:\Logs\TestLog\testLog.csv",FileMode.Create))
    {
        StreamWriter sw = new StreamWriter(fs);
        testLog.ForEach(r => sw.WriteLine(r.ToString()));
        sw.Close();
    }

答案 1 :(得分:1)

我认为您必须最后关闭StreamWriter。 你可以尝试添加sw.Close();吗?在foreach语句之后。

相关问题