Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.ObjectDisposedException: Cannot access a closed Stream

Tags:

c#

.net

Is it true that this does not necessarily mean the stream has been disposed of by code - either in a using or by calling dispose.

The stream could have been closed outside of this code and this exception would still occur?

like image 315
Nick Avatar asked Jun 26 '12 15:06

Nick


2 Answers

This error can also happen if the requestLengthDiskThreshold is smaller than the size of the file you are trying to upload/handle via the stream. This is defined in your web.config:

<httpRuntime maxRequestLength="512000" requestLengthDiskThreshold="512000" />

If you loook at the explanation for the 2nd parameter here:

https://msdn.microsoft.com/en-us/library/system.web.configuration.httpruntimesection.requestlengthdiskthreshold(v=vs.110).aspx

you will see that it sets the input-stream buffering threshold (in kilobytes). The default value is 80KB so if you don't have this value set and you try, for example, to ajax upload the file bigger than 80KB you will get the System.ObjectDisposedException exception since the stream will be closed once the threshold limit is met.

In my case I'm setting the threshold to 500MB...

like image 123
Marko Avatar answered Oct 22 '22 06:10

Marko


The stream could have been closed outside of this code and this exception would still occur?

Yes. For example - This can happen if you wrap a stream within another stream, and dispose of the "wrapper" stream. Many implementations dispose of the stream they are wrapping.

If you then try to write to the "wrapped" stream, you'll receive this error message.

either in a using or by calling dispose.

Also realize that, for objects which have a Close() method, such as Stream, Close and Dispose typically perform the same function. Closing a stream also disposes of it.

like image 41
Reed Copsey Avatar answered Oct 22 '22 06:10

Reed Copsey