System.Net.WebClient Class

Namespace: System.Net
Assembly: System (in System.dll)

Remarks

The WebClient class provides simple, application-level protocols for sending or receiving data from a resource identified by a URI. It is a convenience class that simplifies network operations, providing a single class for many common HTTP, FTP, and file operations. For more complex scenarios or fine-grained control, consider using the classes in the System.Net.Http namespace.

Note: WebClient is generally not recommended for new development. The HttpClient class in the System.Net.Http namespace offers more features, flexibility, and better performance.

Methods

Signature Description
public void DownloadFile(string address, string fileName) Downloads the resource with the specified URI to a local file.
public byte[] DownloadData(string address) Downloads the resource with the specified URI to a byte array.
public string DownloadString(string address) Downloads the resource with the specified URI to a string.
public void UploadFile(string address, string fileName) Uploads a local file to a remote resource.
public byte[] UploadData(string address, byte[] data) Uploads the specified data to a remote resource.
public string UploadString(string address, string data) Uploads the specified string data to a remote resource.
public void Dispose() Releases the unmanaged resources and disposes of the managed resources used by the WebClient.

Properties

Property Description
BaseAddress Gets or sets the base URI for server requests.
Credentials Gets or sets the credentials for server authentication.
Headers Gets the collection of HTTP headers associated with the request.
Encoding Gets or sets the encoding to use for uploading string data and for downloading string data.
IsBusy Gets a value indicating whether the asynchronous operation is in progress.

Example

The following code example demonstrates how to download the content of a web page as a string:

using System;
using System.Net;

public class Example
{
    public static void Main(string[] args)
    {
        string url = "https://www.example.com";
        using (WebClient client = new WebClient())
        {
            try
            {
                string content = client.DownloadString(url);
                Console.WriteLine($"Successfully downloaded content from {url}:");
                Console.WriteLine(content.Substring(0, Math.Min(content.Length, 500)) + "..."); // Print first 500 chars
            }
            catch (WebException e)
            {
                Console.WriteLine($"An error occurred: {e.Message}");
            }
        }
    }
}