.NET API Documentation

System.Net.WebClient Class

Overview
Methods
Properties
Remarks
Example

The WebClient class provides common methods for sending data to and receiving data from a resource identified by a URI.

MethodSignatureDescription
DownloadStringstring DownloadString(string address)Downloads the resource as a string.
DownloadDatabyte[] DownloadData(string address)Downloads the resource as a byte array.
UploadStringstring UploadString(string address, string data)Uploads a string to the resource and returns the response as a string.
UploadFilebyte[] UploadFile(string address, string fileName)Uploads a local file to the resource.
OpenReadStream OpenRead(string address)Opens a readable stream for the resource.
OpenWriteStream OpenWrite(string address)Opens a writable stream for the resource.
DownloadStringAsyncvoid DownloadStringAsync(Uri uri)Begins an asynchronous download of a string.
UploadStringAsyncvoid UploadStringAsync(Uri uri, string method, string data)Begins an asynchronous upload of a string.
PropertyTypeDescription
BaseAddressstringGets or sets the base URI for requests made by the WebClient.
CredentialsICredentialsGets or sets the authentication credentials for the request.
HeadersWebHeaderCollectionGets the collection of HTTP headers associated with the request.
EncodingEncodingGets or sets the encoding used to convert strings to and from bytes.
ProxyIWebProxyGets 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();
    }
}