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.");
}
}