WebClient.OpenReadAsync Method
Asynchronously opens a writable stream for the specified resource.
HttpClient from the System.Net.Http namespace. For more information, see [Why is `WebClient` considered obsolete?](https://docs.microsoft.com/en-us/dotnet/fundamentals/whats-new/dotnet-6/breaking-changes#why-is-webclient-considered-obsolete).
Syntax
public virtual System.IO.Stream OpenReadAsync(
string address
);
public virtual System.IO.Stream OpenReadAsync(
string address,
object userState
);
public virtual System.Threading.Tasks.Task<System.IO.Stream> OpenReadAsync(
string address,
System.Threading.CancellationToken cancellationToken
);
Parameters
| Name | Description |
|---|---|
address |
The URI of the resource to open. |
userState |
An object that distinguishes this asynchronous operation from other operations. |
cancellationToken |
A cancellation token to observe for cancellation requests. |
Returns
A System.IO.Stream object that contains the response stream from the resource.
A System.Threading.Tasks.Task<Stream> object that represents the asynchronous operation.
Exceptions
| Type | Condition |
|---|---|
ArgumentNullException |
address is null. |
UriFormatException |
address is not a valid URI. |
NotSupportedException |
This method is not supported on the current platform. |
WebException |
An error occurred while downloading the resource. |
Remarks
The OpenReadAsync method initiates an asynchronous request to the resource specified by the address parameter.
When you use OpenReadAsync, the method returns a Stream object immediately. You can then read the response data from this stream.
The method is asynchronous, meaning it does not block the calling thread while waiting for the network operation to complete. This is useful for maintaining the responsiveness of your application, especially in UI scenarios.
For newer applications, it is strongly recommended to use HttpClient, which offers a more robust and flexible API for making HTTP requests.
Example
The following example demonstrates how to use OpenReadAsync to download the content of a web page and write it to a file.
using System;
using System.Net;
using System.IO;
using System.Threading.Tasks;
public class Example
{
public async static void DownloadPageContent(string url, string outputPath)
{
using var client = new WebClient();
try
{
using var stream = await client.OpenReadAsync(url);
using var fileStream = new FileStream(outputPath, FileMode.Create);
await stream.CopyToAsync(fileStream);
Console.WriteLine("Content downloaded successfully to " + outputPath);
}
catch (WebException ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
}
}
public static void Main(string[] args)
{
// Example usage:
// DownloadPageContent("https://www.example.com", "example.html");
}
}
OpenReadAsync when you are finished with it to release system resources. Using a using statement ensures this happens automatically.