how to use StreamWriter class properly?

佐手、 提交于 2019-11-28 09:20:25

Whats wrong with your code? If some exception will occur before you close stream, then stream will stay open, and system resources will not be released:

StreamWriter sr = new StreamWriter(streamFolder);
sr.Write(details);
// some exception occurs here 
File.SetAttributes(streamFolder, FileAttributes.Hidden);
sr.Close();

So, you need to be sure, that stream will be closed. This could be achieved by try...finally block:

StreamWriter sr = new StreamWriter(streamFolder);

try 
{
   sr.Write(details);
   // some exception occurs here 
   File.SetAttributes(streamFolder, FileAttributes.Hidden);
}
finally
{
   sr.Close();
}

But StreamWriter implements IDisposable interface, so you can let C# compiler do it automatically for you by wrapping writer usage into using block:

using(StreamWriter sr = new StreamWriter(streamFolder)) 
{
   sr.Write(details);
   // some exception occurs here 
   File.SetAttributes(streamFolder, FileAttributes.Hidden);
}

This code will be compiled as:

StreamWriter sr = new StreamWriter(streamFolder);

try 
{
   sr.Write(details);
   // some exception occurs here 
   File.SetAttributes(streamFolder, FileAttributes.Hidden);
}
finally
{
   if (sr != null)
      sr.Dispose();
}

The only difference between manual implementation is null-check and method Dispose is called instead of Close. But actually when you call Close() or Dispose() same code will be executed:

this.Dispose(true);
GC.SuppressFinalize(this);

You can read more on Dispose method implementation.

You should probably use a using statement:

using (StreamWriter sr = new StreamWriter(streamFolder))
{
    sr.Write(details);
    File.SetAttributes(streamFolder, FileAttributes.Hidden);
}

At the end of the using block, the StreamWriter.Dispose will be called, whether there was an exception or the code ran successfully.

You want to use:

  using (StreamWriter sr = new StreamWriter(streamFolder))
  {
      sr.Write(details); 

      File.SetAttributes(streamFolder, FileAttributes.Hidden); 
  }

You don't need the Close.

Wrap it in a using block

using(StreamWriter sr = new StreamWriter(streamFolder))
{
      sr.Write(details);
      File.SetAttributes(streamFolder, FileAttributes.Hidden);
}

Make sure your naming is good, so streamFolder should probably be an fName. You can also put this code into try-catch-finally, if you feel you can handle some IO (or other) exceptions:

StreamWriter sr;
try
{
    sr = new StreamWriter(streamFolder);
    sr.Write(details);
    File.SetAttributes(streamFolder, FileAttributes.Hidden);
}
catch(IOException ex)
{
    //handling IO
}
finally
{
    if (sr != null)
        sr.Dispose();
}

System.IO.StreamWriter is a System.IDisposable

You have to dispose it. And why do you close something you don't open ?

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