3 out of 12 rated this helpful - Rate this topic

WebClient Class

Provides common methods for sending data to and receiving data from a resource identified by a URI.

Namespace:  System.Net
Assembly:  System (in System.dll)
[ComVisibleAttribute(true)]
public class WebClient : Component

The WebClient type exposes the following members.

  Name Description
Public method Supported by Portable Class Library WebClient Initializes a new instance of the WebClient class.
Top
  Name Description
Public property Supported by Portable Class Library BaseAddress Gets or sets the base URI for requests made by a WebClient.
Public property CachePolicy Gets or sets the application's cache policy for any resources obtained by this WebClient instance using WebRequest objects.
Protected property CanRaiseEvents Gets a value indicating whether the component can raise an event. (Inherited from Component.)
Public property Container Gets the IContainer that contains the Component. (Inherited from Component.)
Public property Supported by Portable Class Library Credentials Gets or sets the network credentials that are sent to the host and used to authenticate the request.
Protected property DesignMode Gets a value that indicates whether the Component is currently in design mode. (Inherited from Component.)
Public property Supported by Portable Class Library Encoding Gets and sets the Encoding used to upload and download strings.
Protected property Events Gets the list of event handlers that are attached to this Component. (Inherited from Component.)
Public property Supported by Portable Class Library Headers Gets or sets a collection of header name/value pairs associated with the request.
Public property Supported by Portable Class Library IsBusy Gets whether a Web request is in progress.
Public property Proxy Gets or sets the proxy used by this WebClient object.
Public property QueryString Gets or sets a collection of query name/value pairs associated with the request.
Public property Supported by Portable Class Library ResponseHeaders Gets a collection of header name/value pairs associated with the response.
Public property Site Gets or sets the ISite of the Component. (Inherited from Component.)
Public property Supported by Portable Class Library UseDefaultCredentials Gets or sets a Boolean value that controls whether the DefaultCredentials are sent with requests.
Top
  Name Description
Public method Supported by Portable Class Library CancelAsync Cancels a pending asynchronous operation.
Public method CreateObjRef Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)
Public method Dispose() Releases all resources used by the Component. (Inherited from Component.)
Protected method Dispose(Boolean) Releases the unmanaged resources used by the Component and optionally releases the managed resources. (Inherited from Component.)
Public method DownloadData(String) Downloads the resource with the specified URI as a Byte array.
Public method DownloadData(Uri) Downloads the resource with the specified URI as a Byte array.
Public method DownloadDataAsync(Uri) Downloads the specified resource as a Byte array. This method does not block the calling thread.
Public method DownloadDataAsync(Uri, Object) Downloads the specified resource as a Byte array. This method does not block the calling thread.
Public method DownloadFile(String, String) Downloads the resource with the specified URI to a local file.
Public method DownloadFile(Uri, String) Downloads the resource with the specified URI to a local file.
Public method DownloadFileAsync(Uri, String) Downloads, to a local file, the resource with the specified URI. This method does not block the calling thread.
Public method DownloadFileAsync(Uri, String, Object) Downloads, to a local file, the resource with the specified URI. This method does not block the calling thread.
Public method DownloadString(String) Downloads the requested resource as a String. The resource to download is specified as a String containing the URI.
Public method DownloadString(Uri) Downloads the requested resource as a String. The resource to download is specified as a Uri.
Public method Supported by Portable Class Library DownloadStringAsync(Uri) Downloads the resource specified as a Uri. This method does not block the calling thread.
Public method Supported by Portable Class Library DownloadStringAsync(Uri, Object) Downloads the specified string to the specified resource. This method does not block the calling thread.
Public method Supported by Portable Class Library Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected method Finalize Releases unmanaged resources and performs other cleanup operations before the Component is reclaimed by garbage collection. (Inherited from Component.)
Public method Supported by Portable Class Library GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
Public method GetLifetimeService Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Protected method GetService Returns an object that represents a service provided by the Component or by its Container. (Inherited from Component.)
Public method Supported by Portable Class Library GetType Gets the Type of the current instance. (Inherited from Object.)
Protected method Supported by Portable Class Library GetWebRequest Returns a WebRequest object for the specified resource.
Protected method GetWebResponse(WebRequest) Returns the WebResponse for the specified WebRequest.
Protected method Supported by Portable Class Library GetWebResponse(WebRequest, IAsyncResult) Returns the WebResponse for the specified WebRequest using the specified IAsyncResult.
Public method InitializeLifetimeService Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Protected method Supported by Portable Class Library MemberwiseClone() Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method MemberwiseClone(Boolean) Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.)
Protected method OnDownloadDataCompleted Raises the DownloadDataCompleted event.
Protected method OnDownloadFileCompleted Raises the DownloadFileCompleted event.
Protected method Supported by Portable Class Library OnDownloadProgressChanged Raises the DownloadProgressChanged event.
Protected method Supported by Portable Class Library OnDownloadStringCompleted Raises the DownloadStringCompleted event.
Protected method Supported by Portable Class Library OnOpenReadCompleted Raises the OpenReadCompleted event.
Protected method Supported by Portable Class Library OnOpenWriteCompleted Raises the OpenWriteCompleted event.
Protected method OnUploadDataCompleted Raises the UploadDataCompleted event.
Protected method OnUploadFileCompleted Raises the UploadFileCompleted event.
Protected method Supported by Portable Class Library OnUploadProgressChanged Raises the UploadProgressChanged event.
Protected method Supported by Portable Class Library OnUploadStringCompleted Raises the UploadStringCompleted event.
Protected method OnUploadValuesCompleted Raises the UploadValuesCompleted event.
Public method OpenRead(String) Opens a readable stream for the data downloaded from a resource with the URI specified as a String.
Public method OpenRead(Uri) Opens a readable stream for the data downloaded from a resource with the URI specified as a Uri
Public method Supported by Portable Class Library OpenReadAsync(Uri) Opens a readable stream containing the specified resource. This method does not block the calling thread.
Public method Supported by Portable Class Library OpenReadAsync(Uri, Object) Opens a readable stream containing the specified resource. This method does not block the calling thread.
Public method OpenWrite(String) Opens a stream for writing data to the specified resource.
Public method OpenWrite(Uri) Opens a stream for writing data to the specified resource.
Public method OpenWrite(String, String) Opens a stream for writing data to the specified resource, using the specified method.
Public method OpenWrite(Uri, String) Opens a stream for writing data to the specified resource, by using the specified method.
Public method Supported by Portable Class Library OpenWriteAsync(Uri) Opens a stream for writing data to the specified resource. This method does not block the calling thread.
Public method Supported by Portable Class Library OpenWriteAsync(Uri, String) Opens a stream for writing data to the specified resource. This method does not block the calling thread.
Public method Supported by Portable Class Library OpenWriteAsync(Uri, String, Object) Opens a stream for writing data to the specified resource, using the specified method. This method does not block the calling thread.
Public method ToString Returns a String containing the name of the Component, if any. This method should not be overridden. (Inherited from Component.)
Public method UploadData(String, Byte[]) Uploads a data buffer to a resource identified by a URI.
Public method UploadData(Uri, Byte[]) Uploads a data buffer to a resource identified by a URI.
Public method UploadData(String, String, Byte[]) Uploads a data buffer to the specified resource, using the specified method.
Public method UploadData(Uri, String, Byte[]) Uploads a data buffer to the specified resource, using the specified method.
Public method UploadDataAsync(Uri, Byte[]) Uploads a data buffer to a resource identified by a URI, using the POST method. This method does not block the calling thread.
Public method UploadDataAsync(Uri, String, Byte[]) Uploads a data buffer to a resource identified by a URI, using the specified method. This method does not block the calling thread.
Public method UploadDataAsync(Uri, String, Byte[], Object) Uploads a data buffer to a resource identified by a URI, using the specified method and identifying token.
Public method UploadFile(String, String) Uploads the specified local file to a resource with the specified URI.
Public method UploadFile(Uri, String) Uploads the specified local file to a resource with the specified URI.
Public method UploadFile(String, String, String) Uploads the specified local file to the specified resource, using the specified method.
Public method UploadFile(Uri, String, String) Uploads the specified local file to the specified resource, using the specified method.
Public method UploadFileAsync(Uri, String) Uploads the specified local file to the specified resource, using the POST method. This method does not block the calling thread.
Public method UploadFileAsync(Uri, String, String) Uploads the specified local file to the specified resource, using the POST method. This method does not block the calling thread.
Public method UploadFileAsync(Uri, String, String, Object) Uploads the specified local file to the specified resource, using the POST method. This method does not block the calling thread.
Public method UploadString(String, String) Uploads the specified string to the specified resource, using the POST method.
Public method UploadString(Uri, String) Uploads the specified string to the specified resource, using the POST method.
Public method UploadString(String, String, String) Uploads the specified string to the specified resource, using the specified method.
Public method UploadString(Uri, String, String) Uploads the specified string to the specified resource, using the specified method.
Public method Supported by Portable Class Library UploadStringAsync(Uri, String) Uploads the specified string to the specified resource. This method does not block the calling thread.
Public method Supported by Portable Class Library UploadStringAsync(Uri, String, String) Uploads the specified string to the specified resource. This method does not block the calling thread.
Public method Supported by Portable Class Library UploadStringAsync(Uri, String, String, Object) Uploads the specified string to the specified resource. This method does not block the calling thread.
Public method UploadValues(String, NameValueCollection) Uploads the specified name/value collection to the resource identified by the specified URI.
Public method UploadValues(Uri, NameValueCollection) Uploads the specified name/value collection to the resource identified by the specified URI.
Public method UploadValues(String, String, NameValueCollection) Uploads the specified name/value collection to the resource identified by the specified URI, using the specified method.
Public method UploadValues(Uri, String, NameValueCollection) Uploads the specified name/value collection to the resource identified by the specified URI, using the specified method.
Public method UploadValuesAsync(Uri, NameValueCollection) Uploads the data in the specified name/value collection to the resource identified by the specified URI. This method does not block the calling thread.
Public method UploadValuesAsync(Uri, String, NameValueCollection) Uploads the data in the specified name/value collection to the resource identified by the specified URI, using the specified method. This method does not block the calling thread.
Public method UploadValuesAsync(Uri, String, NameValueCollection, Object) Uploads the data in the specified name/value collection to the resource identified by the specified URI, using the specified method. This method does not block the calling thread, and allows the caller to pass an object to the method that is invoked when the operation completes.
Top
  Name Description
Public event Disposed Occurs when the component is disposed by a call to the Dispose method. (Inherited from Component.)
Public event DownloadDataCompleted Occurs when an asynchronous data download operation completes.
Public event DownloadFileCompleted Occurs when an asynchronous file download operation completes.
Public event Supported by Portable Class Library DownloadProgressChanged Occurs when an asynchronous download operation successfully transfers some or all of the data.
Public event Supported by Portable Class Library DownloadStringCompleted Occurs when an asynchronous resource-download operation completes.
Public event Supported by Portable Class Library OpenReadCompleted Occurs when an asynchronous operation to open a stream containing a resource completes.
Public event Supported by Portable Class Library OpenWriteCompleted Occurs when an asynchronous operation to open a stream to write data to a resource completes.
Public event UploadDataCompleted Occurs when an asynchronous data-upload operation completes.
Public event UploadFileCompleted Occurs when an asynchronous file-upload operation completes.
Public event Supported by Portable Class Library UploadProgressChanged Occurs when an asynchronous upload operation successfully transfers some or all of the data.
Public event Supported by Portable Class Library UploadStringCompleted Occurs when an asynchronous string-upload operation completes.
Public event UploadValuesCompleted Occurs when an asynchronous upload of a name/value collection completes.
Top

The WebClient class provides common methods for sending data to or receiving data from any local, intranet, or Internet resource identified by a URI.

The WebClient class uses the WebRequest class to provide access to resources. WebClient instances can access data with any WebRequest descendant registered with the WebRequest.RegisterPrefix method.

Note Note

By default, the .NET Framework supports URIs that begin with http:, https:, ftp:, and file: scheme identifiers.

The following table describes WebClient methods for uploading data to a resource.

Method

Description

OpenWrite

Retrieves a Stream used to send data to the resource.

OpenWriteAsync

Retrieves a Stream used to send data to the resource, without blocking the calling thread.

UploadData

Sends a byte array to the resource and returns a Byte array containing any response.

UploadDataAsync

Sends a Byte array to the resource, without blocking the calling thread.

UploadFile

Sends a local file to the resource and returns a Byte array containing any response.

UploadFileAsync

Sends a local file to the resource, without blocking the calling thread.

UploadValues

Sends a NameValueCollection to the resource and returns a Byte array containing any response.

UploadValuesAsync

Sends a NameValueCollection to the resource and returns a Byte array containing any response, without blocking the calling thread.

UploadString

Sends a String to the resource, without blocking the calling thread.

UploadStringAsync

Sends a String to the resource, without blocking the calling thread.

The following table describes WebClient methods for downloading data from a resource.

Method

Description

OpenRead

Returns the data from a resource as a Stream.

OpenReadAsync

Returns the data from a resource, without blocking the calling thread.

DownloadData

Downloads data from a resource and returns a Byte array.

DownloadDataAsync

Downloads data from a resource and returns a Byte array, without blocking the calling thread.

DownloadFile

Downloads data from a resource to a local file.

DownloadFileAsync

Downloads data from a resource to a local file, without blocking the calling thread.

DownloadString

Downloads a String from a resource and returns a String.

DownloadStringAsync

Downloads a String from a resource, without blocking the calling thread.

You can use the CancelAsync method to cancel asynchronous operations that have not completed.

A WebClient instance does not send optional HTTP headers by default. If your request requires an optional header, you must add the header to the Headers collection. For example, to retain queries in the response, you must add a user-agent header. Also, servers may return 500 (Internal Server Error) if the user agent header is missing.

AllowAutoRedirect is set to true in WebClient instances.

Notes to Inheritors

Derived classes should call the base class implementation of WebClient to ensure the derived class works as expected.

The following code example takes the URI of a resource, retrieves it, and displays the response.


using System;
using System.Net;
using System.IO;

public class Test
{
    public static void Main (string[] args)
    {
        if (args == null || args.Length == 0)
        {
            throw new ApplicationException ("Specify the URI of the resource to retrieve.");
        }
        WebClient client = new WebClient ();

        // Add a user agent header in case the 
        // requested URI contains a query.

        client.Headers.Add ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");

        Stream data = client.OpenRead (args[0]);
        StreamReader reader = new StreamReader (data);
        string s = reader.ReadToEnd ();
        Console.WriteLine (s);
        data.Close ();
        reader.Close ();
    }
}


.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library
  • WebPermission  

    to access the requested URI or any URI that the request is redirected to. Associated enumeration: Connect.

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Getting a response code is a faff.
See link for information about getting a proper HTTP status code from a request. http://stackoverflow.com/questions/1015020/how-to-read-an-asp-net-internal-server-error-description-with-net
Example doesn't work for .NET 4
the example works for earlier versions, but not in .NET 4 VS 2010
UploadString does block the calling thread
UploadString in the remarks should have "Sends a String to the resource" and not "Sends a String to the resource, without blocking the calling thread." as it does block the calling thread.
WebClient (with Proxy configured in IE) is broken in .net 4?
The following code download the yahoo website file with target .net 2.0, 3.0, 3.5 with proxy configured in IE. But it does not work for target .net 4. I'm using VS2010. How could it be broken in .net 4?!
 
 
 
using System;
using System.Net;
using System.IO;
namespace PacProxyUsage
{
 /// <summary>
 /// Summary description for ProxyTest.
 /// </summary>
 class ProxyTest
 {
  /// <summary>
  /// The main entry point for the application.
  /// </summary>
  [STAThread]
  static void Main(string[] args)
  {
          
            string DestinationUrl = "http://www.yahoo.com";
           
          
            try {
                WebClient wc = new WebClient();
            
                String s = wc.DownloadString(DestinationUrl);
                Console.WriteLine ( "Request was successful?"  + s);
            }catch ( Exception ex ){
                Console.WriteLine ( "Error: {0}", ex.Message );
            }finally{
                
            }
            Console.ReadLine();
  }
 }
}