2
votes

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.

3
If you close and dispose that seems strange, can you paste some sample code? - Edwin Jarvis
I agree. Are there any there stream operations going on here? - BC.
I have a development web site which is opening a file in the production web site. It seems I have to edit the web.config in the production web site to restart the web application and release the file even though it is the development web site that opened it. - rsrobbins

3 Answers

4
votes

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

1
votes

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.

0
votes

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