Fog Creek Software
Discussion Board




Welcome! and rules

Joel on Software

BinaryReader.Close

This will surely be a newbie question but....

I am using C# is ASP.NET to upload files using a webform into a SQL database.

My input file is called UploadedFile (for example).

I execute the following code:
br = new BinaryReader(UploadedFile.PostedFile.InputStream);
...
some code to upload the br input the appropriate spot in the database
...
br.Close()
...
some other code.

The problem is, once I execute br.Close(), it seems that ASP.NET empties all of UploadedFile.

All I want to do is manage my resources and close everything I open.

This is not a huge deal because once I saw what was going on, I reworked the code to get all the other relevant info before (ie: filetype, file size, file name, etc...) writing to the database.

Any explanation would be welcome.

Thanks in advance.

Charles Reich
Tuesday, August 12, 2003

It's by design:
From http://msdn.microsoft.com/library/en-us/cpref/html/frlrfsystemiobinaryreaderclassclosetopic.asp
"BinaryReader.Close - Closes the current reader and the underlying stream..."

Duncan Smart
Wednesday, August 13, 2003

Duncan,

Do I have to worry about calling br.close() in the same way that I have to close database connections?

Charles Reich
Wednesday, August 13, 2003

A rule of thumb is that if it implements IDisposable then call the Dispose() or Close() method when you're done. Use the using statement to do this for you, eg:

  using(BinaryReader br = new BinaryReader(...))
  {
      //... do stuff with br, no need to call Dispose()
      //... as this will be done automatically at the end
      //... of the block.
  }

(it gets compile to a try...finally with a IDisposable.Dispose in the finally)

I doubt anything drastic would have happened had you not done so, they would have been freed by garbage collection eventually. The key with db connections though is closing them ASAP rather than waiting for a garbage collection so it's much more important there.

Duncan Smart
Wednesday, August 13, 2003

*  Recent Topics

*  Fog Creek Home