Wednesday, April 6, 2011

.NET StreamReader Won't Close

I'm using a RTF file as a template for an ASP.NET web application. My VB.NET code reads the file using a StreamReader, replaces some strings, and creates a new Word document with data from the database. My code closes and disposes of the StreamReader. However, when I attempt to upload a revised RTF file to the web server I get an error, "Cannot open the file for writing". So obviously the file remains open long after the ASP.NET page has run.

How can I force the StreamReader to close? Even editing the web.config file to force the web application to restart isn't enough to kill the lock on this file.

From stackoverflow
  • It seems odd if it's hanging on even after a close/dispose. Are you using a FileStream along with the StreamReader? Generally, I use a FileStream to control access to the file and feed that to the StreamReader, a la:

    FileStream fsIn = new FileStream("path",FileMode.Open, FileAccess.Read, FileShare.None);
    StreamReader srIn = new StreamReader(fsIn, System.Text.Encoding.Default);
    
    //...do stuff....
    
    srIn.close();
    srIn.Dispose();
    fsIn.close();
    fsIn.Dispose();
    

    Better yet, if you're limiting the use of your StreamReader to one method, stick the Close/Dispose in a Finally.

    Augusto Radtke : I would also suggest to use "using" directive.
    AJ : What can I say? I'm old fashioned :-)
    Augusto Radtke : That makes me think that I never really tested if Dispose() closes the stream, but I trust the documentation!
  • consider using the "using" idiom, also available in VB.net

    using(StreamReader reader = new StreamReader(...)) {
    
    }
    

    the stream will get closed, even if exception is thrown

    Consider closing all IDisposable implementations like this

  • Make sure the stream is closed in finally.

    FileStream fsIn = null;
    StreamReader srIn = null; 
    
    try
    {
      fsIn = new FileStream("path",FileMode.Open, FileAccess.Read, FileShare.None);
      srIn = new StreamReader(fsIn, System.Text.Encoding.Default);
    
      //...do stuff....
    
    }
    catch (Exception ex)
    {
    }
    finally
    {
      srIn.close();
      srIn.Dispose();
      fsIn.close();
      fsIn.Dispose();
    }
    

0 comments:

Post a Comment