System.ObjectDisposedException: Cannot access a closed Stream
So I will make my comment an answer: Yes, a stream could just as well be closed from outside your code, so make sure you check for a System.ObjectDisposedException
.
There are several occasions this could happen: imagine for example a stream associated with a network connection and the connection is suddenly interrupted. Depending on the implementation this could close the stream and throw that particular exception if the stream is accessed.
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.
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...