Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use StreamWriter class properly?

I am using StreamWriter class for file operations, are there any problems in this code that I am not seeing?

Such as do I need to put it into a try catch finally block?

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

File.SetAttributes(streamFolder, FileAttributes.Hidden);
sr.Close();
like image 700
vettori Avatar asked Jul 13 '12 08:07

vettori


3 Answers

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.

like image 56
Sergey Berezovskiy Avatar answered Oct 21 '22 11:10

Sergey Berezovskiy


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.

like image 27
Daniel Sklenitzka Avatar answered Oct 21 '22 11:10

Daniel Sklenitzka


You want to use:

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

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

You don't need the Close.

like image 5
John Saunders Avatar answered Oct 21 '22 10:10

John Saunders