我有一个来自对象的属性数组,我希望将其附加到文本文件中。
这是我的代码:
StreamWriter Writer = new StreamWriter("Cars.txt");
for (int i = 0; i < 4; i++)
{
Writer.Write(CarProps[i]);
}
我手动向文本文件添加了东西,但是当我运行程序时,文本文件显示为空白。
答案 0 :(得分:3)
使用using
语句刷新编写器:
using(var writer = new StreamWriter("Cars.txt"))
{
for (int i = 0; i < 4; i++)
{
writer.Write(CarProps[i]);
}
}
如果您未将StreamWriter.AutoFlush
设置为true
,则不会立即写入该流。因此,您必须手动拨打Flush
或Close
。 Flush
会调用Dispose
,using
会调用{/ 1}}。