文本文件中C#中的StreamWriter限制
我有一个包含100行的数组列表. 当我尝试将其导出到文本文件(txt)时,输出仅为84行,它停在第84行的中间. 当我查看文件大小时,它恰好显示了4.00KB,好像流写入器存在某种限制.我尝试使用其他参数等,但是它一直在发生.
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 I looked at the file size it showed exactly sharp 4.00KB as if there is some kind of a limit to the stream writer. I tried using different parameters etc. but it kept happening.
这是代码:
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");
感谢您的帮助!
您需要调用StreamWriter.Flush
或将StreamWriter.AutoFlush
设置为true.就是说,如果您使用using
陈述,那么一切都会正常运行.
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);
}
}
使用语句调用Dispose
,这会将缓冲区刷新到FileStream
,并关闭文件流.因此,您无需手动关闭它.
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.
然后,我建议使用List<T>
而不是ArrayList
. ArrayList
不应使用,它不是类型安全的,如果您使用的是.Net2.0或更高版本,则应避免使用该语言.
Then I recommend List<T>
over ArrayList
. ArrayList
shouldn't be used, it is not type safe and should be avoided if you're in .Net2.0 or greater.
还可以考虑使用 File.WriteAllLines 方法,因此您不需要这么多代码行.一切都由WriteAllLines
方法本身管理.
Also consider using File.WriteAllLines method, so that you don't need these many lines of code. Everything is managed by WriteAllLines
method itself.