System.Net.WebClient Class
The WebClient
class provides common methods for sending data to and receiving data from a resource identified by a URI.
- Simple API for downloading and uploading data.
- Supports synchronous and asynchronous operations.
- Handles HTTP, FTP, and file protocols.
Method | Signature | Description |
---|---|---|
DownloadString | string DownloadString(string address) | Downloads the resource as a string. |
DownloadData | byte[] DownloadData(string address) | Downloads the resource as a byte array. |
UploadString | string UploadString(string address, string data) | Uploads a string to the resource and returns the response as a string. |
UploadFile | byte[] UploadFile(string address, string fileName) | Uploads a local file to the resource. |
OpenRead | Stream OpenRead(string address) | Opens a readable stream for the resource. |
OpenWrite | Stream OpenWrite(string address) | Opens a writable stream for the resource. |
DownloadStringAsync | void DownloadStringAsync(Uri uri) | Begins an asynchronous download of a string. |
UploadStringAsync | void UploadStringAsync(Uri uri, string method, string data) | Begins an asynchronous upload of a string. |
Property | Type | Description |
---|---|---|
BaseAddress | string | Gets or sets the base URI for requests made by the WebClient. |
Credentials | ICredentials | Gets or sets the authentication credentials for the request. |
Headers | WebHeaderCollection | Gets the collection of HTTP headers associated with the request. |
Encoding | Encoding | Gets or sets the encoding used to convert strings to and from bytes. |
Proxy | IWebProxy | Gets or sets the proxy used for requests. |
The WebClient
class simplifies common tasks such as downloading files, uploading data, and interacting with web services. It automatically handles the underlying WebRequest
objects and provides higher-level methods.
When using asynchronous methods, handle the DownloadStringCompleted
, UploadStringCompleted
, and related events to process results and errors.
Downloading a Web Page
using System;
using System.Net;
class Program
{
static void Main()
{
using (WebClient client = new WebClient())
{
client.Encoding = System.Text.Encoding.UTF8;
string html = client.DownloadString("https://example.com");
Console.WriteLine(html);
}
}
}
Uploading JSON Data (Async)
using System;
using System.Net;
using System.Text;
class AsyncUpload
{
static void Main()
{
WebClient client = new WebClient();
client.Headers[HttpRequestHeader.ContentType] = "application/json";
client.UploadStringCompleted += (s, e) =>
{
if (e.Error == null)
Console.WriteLine("Response: " + e.Result);
};
string json = "{\"name\":\"John\",\"age\":30}";
client.UploadStringAsync(new Uri("https://api.example.com/users"), "POST", json);
Console.ReadLine();
}
}