Limit StreamWriter in C # in a text file
I have a list of arrays containing 100 lines. When I try to export it to a text file (txt), the output is only 84 lines and stops in the middle of the 84th line. When I looked at the file size it showed exactly 4.00KB, as if there was some kind of limit for the stream writer. I tried to use different parameters etc. but it kept on.
Here is the code:
FileStream fs = new FileStream(path, FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
ArrayList chartList = GetChart(maintNode);
foreach (var line in chartList)
{
sw.WriteLine(line);
}
fs.Close();
Console.WriteLine("Done");
Thanks for the help!
source to share
You need to call StreamWriter.Flush
or set StreamWriter.AutoFlush
to true. However, if you are using 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 the statements calls Dispose
which will clear the buffer before FileStream
and also close the file stream. Therefore, you do not need to close it manually.
Then I recommend List<T>
over ArrayList
. ArrayList
should not be used, it is not type safe and should be avoided if you are on .Net2.0 or higher.
Also consider using the File.WriteAllLines method so that you don't need many lines of code. Everything is controlled by the method itself WriteAllLines
.
source to share