Search code examples
c#arraylistfilestream

Trying to write list items to text file but the file ends up blank


I have a class TestLogEntry whose ToString() method I've overridden as follows:

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

I have a List<TestLogEntry> instance testLog that I'm trying to read into a text file:

    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 clearly has data in it when I examine it at a breakpoint at the ForEach statement, but after this completes, the file is blank. How do I write the list contents to the file?


Solution

  • I think you have to close StreamWriter at the end. Can you try adding sw.Close(); after foreach statement.