HttpResponseMessage.Content.ReadAsStreamAsync()
Summary
Reads the HTTP response content as a stream.
public Task<Stream> ReadAsStreamAsync(CancellationToken cancellationToken = default)
Parameters
-
cancellationToken
The token to monitor for cancellation requests.
Returns
-
Task<Stream>
A task that represents the asynchronous read operation. The value of the task contains the response stream.
Exceptions
-
ObjectDisposedException
The
HttpResponseMessagehas been disposed. -
InvalidOperationException
The content has already been read.
Remarks
This method is used to read the response body as a stream. This is particularly useful for large responses where you want to process the data in chunks rather than loading the entire content into memory at once.
It's important to ensure that the stream is properly disposed of after use to release resources.
Calling this method multiple times on the same response will throw an InvalidOperationException because the content can only be read once.
Example
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
public class Example
{
public static async Task ReadContentAsStreamAsync()
{
using (var httpClient = new HttpClient())
{
try
{
var response = await httpClient.GetAsync("https://www.example.com");
response.EnsureSuccessStatusCode(); // Throw if not success
using (Stream responseStream = await response.Content.ReadAsStreamAsync())
using (var reader = new StreamReader(responseStream))
{
string content = await reader.ReadToEndAsync();
Console.WriteLine(content);
}
}
catch (HttpRequestException e)
{
Console.WriteLine($"Request error: {e.Message}");
}
catch (Exception e)
{
Console.WriteLine($"An error occurred: {e.Message}");
}
}
}
}