[英]StreamWriter limit in C# in text file
I have an array list which contains 100 lines. 我有一个包含100行的数组列表。 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.
当我尝试将其导出到文本文件(txt)时,输出只有84行,它停在第84行的中间。 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.
当我查看文件大小时,它显示了非常清晰的4.00KB,好像对流编写器有某种限制。 I tried using different parameters etc. but it kept happening.
我尝试使用不同的参数等,但它一直在发生。
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! 谢谢您的帮助!
You need to call StreamWriter.Flush
or set StreamWriter.AutoFlush
to true. 您需要调用
StreamWriter.Flush
或将StreamWriter.AutoFlush
设置为true。 That said, if you use using
statment, everything should work fine. 也就是说,如果你使用
using
statment,一切都应该正常工作。
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. 使用语句调用
Dispose
将缓冲区刷新到FileStream
并关闭文件流。 So you don't need to close it manually. 所以你不需要手动关闭它。
Then I recommend List<T>
over ArrayList
. 然后我推荐
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. 不应该使用
ArrayList
,它不是类型安全的,如果你在.Net2.0或更高版本,应该避免使用。
Also consider using File.WriteAllLines method, so that you don't need these many lines of code. 还要考虑使用File.WriteAllLines方法,这样就不需要这么多行代码了。 Everything is managed by
WriteAllLines
method itself. 一切都由
WriteAllLines
方法本身管理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.