StreamWriter limit in C# in text file

后端 未结 1 812
天涯浪人
天涯浪人 2020-12-20 18:10

I have an array list which contains 100 lines. When i try to export it into a text file (txt), the output is only 84 lines and it stops in the middle of the 84th line. When

1条回答
  •  时光说笑
    2020-12-20 18:54

    You need to call StreamWriter.Flush or set StreamWriter.AutoFlush to true. That said, if you use using statment, everything should work fine.

    using(StreamWriter sw = new StreamWriter(fs))
    {
        ArrayList chartList = GetChart(maintNode);    
        foreach (var line in chartList)
        {
            sw.WriteLine(line);
        }
    }
    

    Using statement calls Dispose which will flush the buffer to the FileStream and also closes the file stream. So you don't need to close it manually.

    Then I recommend List over ArrayList. ArrayList shouldn't be used, it is not type safe and should be avoided if you're in .Net2.0 or greater.

    Also consider using File.WriteAllLines method, so that you don't need these many lines of code. Everything is managed by WriteAllLines method itself.

    0 讨论(0)
提交回复
热议问题