c# using statement and StreamWriter

雨燕双飞 提交于 2019-12-10 17:44:19

问题


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.

Anybody knows the reason?


回答1:


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();



回答2:


StreamWriter c = new StreamWriter(@"C:\Users\rxxx\Desktop\important.txt", true);
// you need to write something to see 
c.WriteLine("hello");

if you use using statement it will dispose StreamWriter object automatically. But when you not having using statement you need to manually do the dispose of StreamWriter object. In that case also make sure even on exception case you are disposing object correctly. so you can do as below

StreamWriter c =null;
try
{
  c = new StreamWriter(fileFullPath, true);
  c.WriteLine("hello");
}
finally
{
  if (c!= null)
      c.Close();
}



回答3:


If you don't use using statement, the program does not flush the data from the buffer into the file. That's why "hello" is not written in the file when you open it in the notepad. You may explicitly flush the buffer in order to have your data written into the file:

 StreamWriter c = new StreamWriter(@"C:\Users\xxx\Desktop\important.txt", true)
 c.WriteLine("hello");
 c.Flush();

However, you still need to dispose the stream. But if you use Dispose() method, it automatically flushes the buffer (by calling Flush() method) so you don't need to use Flush()!

By using 'using' statement, not only it flushes the buffer but also it release the stream appropriately and you don't need to write Dispose() explicitly. That's the best way to do it.




回答4:


using statement is "ENSURE" the object in the scope will be Disposed [MSDN]:http://msdn.microsoft.com/en-us/library/yh598w02.aspx

using (StreamWriter c = new StreamWriter(@"C:\Users\xxx\Desktop\important.txt", true))
{
  c.WriteLine("hello");
}

If you don't use using statement , I still recommended use try statement

try
{
  StreamWriter c = new StreamWriter(@"C:\Users\xxx\Desktop\important.txt", true);
}
finally
{
  c.Close();
}


来源:https://stackoverflow.com/questions/16514530/c-sharp-using-statement-and-streamwriter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!