"stream was not readable" ArgumentException when using ReadAsStreamAsync with StreamReader

I have the following code snippet for reading and processing an Http request request response using StreamReader:

try
{
    Stream stream = await ExecuteRequestAsync(uriBuilder.Uri, HttpMethod.Get).ConfigureAwait(false);
    if (stream != null)
    {
        using (StreamReader sr = new StreamReader(stream))
        {
            using (JsonTextReader reader = new JsonTextReader(sr))
            {
                ...
            }
        }
    }
}
catch (Exception ReadingStreamException)
{

}

private async Task<stream> ExecuteRequestAsync(Uri uri, HttpMethod method)
{
    Stream stream;
    using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage(method, uri))
    {
    try
    {
        stopwatch.Start();
        using (HttpResponseMessage responseMessage = await this.httpClient.SendAsync(httpRequestMessage).ConfigureAwait(false))
        {
            stream = await responseMessage.Content.ReadAsStreamAsync().ConfigureAwait(false);
        }
    }
    catch(Exception GettingStreamException)
    {
        // Error checking code
    }

    return stream;
}

A line using (StreamReader sr = new StreamReader(stream))throws an exception in a ReadStreamException of type ArgumentException with a detail of "Stream was not readable". Is there something wrong with the above code?

+4
source share
1 answer

This is because when you have it HttpResponseMessage, it provides the underlying stream. From source :

private HttpContent content;
protected virtual void Dispose(bool disposing)
{
    if (disposing && !disposed)
    {
        disposed = true;
        if (content != null)
        {
            content.Dispose();
        }
    }
}

, HttpResponseMessage, , StreamReader. :

private async Task<Stream> ExecuteRequestAsync(Uri uri, HttpMethod method)
{
    Stream stream = null;
    using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage(method, uri))
    {
       try
       {
          stopwatch.Start();
          HttpResponseMessage responseMessage = await httpClient
                                                      .SendAsync(httpRequestMessage)
                                                      .ConfigureAwait(false);

          stream = await responseMessage.Content.ReadAsStreamAsync()
                                                .ConfigureAwait(false);
       }
       catch(Exception GettingStreamException)
       {
          // Error checking code
       }  
    }
    return stream;
}
+7

All Articles