I have the following code that works as expected. Below that I thought I would add some using statements to make sure everything is disposed of correctly but when i do I get a No data received error page in chrome. If this is because the using statement is disposing(only possibility I could think of...) of the webresponse object how can I return the stream and dispose of webresponse properly? The stream is being returned when a call is being made to a web service this code is a apart of, this results in a file uploading to the client. At least it works in the first example given.
public Stream test(string fileName) //this works fine
{
WebResponse webResponse = webRequest.GetResponse();
Stream stream = webResponse.GetResponseStream();
context.OutgoingResponse.Headers["Content-Disposition"] = string.Format("filename= {0}", fileName);
return stream;
}
public Stream test(string fileName)///gives No data recieved error in chrome
{
WebResponse webResponse;
using(webResponse = webRequest.GetResponse())
{
Stream stream = webResponse.GetResponseStream();
context.OutgoingResponse.Headers["Content-Disposition"] = string.Format("filename= {0}", fileName);
return stream;
}
}
I have no idea in what kind of context you are running this code and what you do with that stream but here is my reasoning.
WebResponse
is IDisposable
which means that when you put it into a using
statement, it will get disposed at the end of the scope.
webResponse
.webResponse
disposes all IDisposable
s of its own when it gets disposed.webResponse
disposes the response stream: stream
.test
function returns stream
.stream
is unusable because it had been disposed.Edit:
Answer to your comment:
That's how IDisposable
objects are expected to work as defined in http://msdn.microsoft.com/en-us/library/system.idisposable(v=vs.110).aspx
Here is a typical IDisposable
class implementation:
// ExampleClass is similar to WebResponse
public class ExampleClass: IDisposable
{
private IDisposable somethingDisposable;
private bool disposed = false;
public ExampleClass()
{
somethingDisposable = new ...
...
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
// Check to see if Dispose has already been called.
if(!this.disposed)
{
if(disposing)
{
// Your stream is disposed similar to
// what happens here:
// IDisposable objects dispose all managed/unmanaged
// resources that they have in their Dispose function.
somethingDisposable.Dispose();
}
disposed = true;
}
}
// This is similar to WebResponse.GetResponseStream
public IDisposable GetSomethingDisposable()
{
return somethingDisposable;
}
}
public static void Main()
{
IDisposable d;
using(var e = new ExampleClass()) {
d = e.GetSomethingDisposable();
}
// here both e and d are disposed.
}