c# using 语句和StreamWriter [英] c# using statement and StreamWriter
问题描述
我正在使用 StreamWriter
将内容写入记事本.我发现如果我没有单独使用语句和实例 StreamWriter
.该方法无法运行.有人知道原因吗?
I am using a StreamWriter
to write things into notepad. And I discover if I am not using statement and instance the StreamWriter
alone. The method is unable to run. Does anybody know the reason?
static void Main(string[] args)
{
//StreamWriter c = new StreamWriter(@"C:\Users\rxxx\Desktop\important.txt", true);
using (StreamWriter c = new StreamWriter(@"C:\Users\xxx\Desktop\important.txt", true))
{
c.WriteLine("hello");
}
这可以运行.但是,如果我改为运行注释部分.记事本什么也没显示.
This can be run. But if I run the remarked part instead. The Notepad shows nothing.
有人知道原因吗?
推荐答案
因为当你在 using 中使用 object 时,它会调用 Dispose 方法,而在 StreamWriter 的情况下它会调用 Fush on对象以及这导致数据写入文件.你可以这样写你的代码:
Because when you use object in using which is good practice, it calls Dispose method and in the case of StreamWriter it call Fush on object as well which causes data to be written in file. you could write your code like this:
var c = new StreamWriter(@"C:\Test\important.txt", true);
c.AutoFlush = true;
c.WriteLine("hello");
c.Dispose();
这篇关于c# using 语句和StreamWriter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!