Search code examples
c#disposeusing

How to Keep Stream Alive Just Long Enough


I have a function that ends with the block shown below.

using (var stream = new MemoryStream(someBytes))
{
    var result = new HttpResponseMessage { Content = new StreamContent(stream) };
    return result;
}

However, in another file, this result is used in a line like so:

var justSomeString = returnedResultFromAbove.Content.ReadAsStringAsync().Result;

This causes the following error:

System.Net.Http.HttpRequestException: Error while copying content to a stream. ---> System.ObjectDisposedException: Cannot access a closed Stream.

What is the best way around this problem? Should I just not wrap my MemoryStream in a using block? Is there a way to keep it open just long enough to be read and then disposed?


Solution

  • Your stream is wrapped by the using statement. The using statement will dispose the stream as soon as exit the method. In order to do what you want you need to pass the dispose responsability to the caller. You need to place the using statement in the caller method.

    using(var stream = GetMyStream())
    {
       // do some work
    }