1

I have been reading some other posts about streams not being accessible. I wanted to see if my understanding was correct and also if the workaround is valid.

So I am getting a Stream back from an http call and if I just assign it to my return variable then I get an exception Cannot access a closed Stream in the calling function. Is this because of the Using? Is that causing the Stream to get closed once the method is exited?

My workaround is to copy the Stream fully to another var and then return that Stream. That seems to work because the entire stream contents are passed to the new var and then that is passed to the calling routine.

Am I on the right path?

using (HttpResponseMessage httpResponseMsg = await httpClient.SendAsync(request, cxlToken))
{
    if (httpResponseMsg.IsSuccessStatusCode)
    {
        Stream pdfStream = await httpResponseMsg.Content.ReadAsStreamAsync();
        Debug.Print("StatusCode={0}", httpResponseMsg.StatusCode);
        Debug.Print("pdfStream.Length={0}", pdfStream.Length);

        //the response is a PDF Stream object
        restDs.ResponseType = RestDataType.Stream;

        //Calling routine will throw System.ObjectDisposedException: Cannot access a closed Stream.
        //stream is closed as soon as we exit the method ???
        restDs.ResponseContent = pdfStream;

        //copy the stream to another var and it should work.
        //Stream strm = new MemoryStream(); 
        //await pdfStream.CopyToAsync(strm);
        //await strm.FlushAsync();
        //strm.Position = 0;
        //restDs.ResponseContent = strm;

        //return the RestDataset class
        return restDs;
    }
    else
    {
        throw new Exception("Invalid return status.");
    }
}
sinDizzy
  • 1,300
  • 7
  • 28
  • 60
  • `HttpResponseMessage` will dispose its stream, just remove the `using` and rely on `restDs` to do the disposal. – Charlieface Aug 05 '22 at 13:25
  • This is basically a duplicate of https://stackoverflow.com/questions/27715327/when-or-if-to-dispose-httpresponsemessage-when-calling-readasstreamasync By placing `HttpResponseMessage` in a using you are disposing of it. You can just return the stream and dispose of it later when you are finished with it. – robs Aug 07 '22 at 12:19
  • Does this answer your question? [When or if to Dispose HttpResponseMessage when calling ReadAsStreamAsync?](https://stackoverflow.com/questions/27715327/when-or-if-to-dispose-httpresponsemessage-when-calling-readasstreamasync) – Charlieface Aug 08 '22 at 01:39
  • Yes I think that is what I was looking for so thanks. I think what I'm going to do for my particular situation is to convert the stream to a byte array in my routine. The stream is small (under 2MB), other APIs in the collection return a byte array, and I can manage all the Http stuff before returning the data to the user. – sinDizzy Aug 08 '22 at 13:24

0 Answers0