39 out of 65 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
/** @attribute ComVisibleAttribute(true) */ 
public class WebClient extends Component
ComVisibleAttribute(true) 
public class WebClient extends Component

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.

NoteNote

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 ();
    }
}

  • WebPermission  to access the requested URI or any URI that the request is redirected to. Associated enumeration: Connect.
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.

.NET Framework

Supported in: 2.0, 1.1, 1.0
Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Cookies

You can extend this to use cookies, which it makes it much more useful. (I adapted this code to VB.net from some C# I found on the web)

Public Class WebClientEx
    Inherits WebClient
    Private ReadOnly cc As New CookieContainer

    Protected Overrides Function GetWebRequest(address As Uri) As WebRequest
        Dim wr As WebRequest = MyBase.GetWebRequest(address)
        Dim hwr As HttpWebRequest = wr
        If hwr IsNot Nothing Then
            hwr.CookieContainer = Me.cc
        End If
        Return wr
    End Function

End Class

This probably isn't the object you want
This initially appears to be a high-level object, but blocks access to high-level HttpWebRequest properties like CookieContainer, IfModifiedSince, AllowAutoRedirect, UserAgent, Referer, ContentType and Encoding; and high-level HttpWebResponse properties like LastModified, ContentType and Encoding. Instead, you have to add or retrieve these headers as strings, manually providing or consuming any dates in the obscure HTTP header format, and parsing the Encoding from the Content-Type.

Without cookies, WebClient isn't well-suited to most tasks requiring multiple requests. Without the other headers mentioned, it is also not well-suited to nontrivial requests.

WebClient also doesn't provide static methods for simple requests, but instead requires management of an instance object, so it isn't really optimized for trivial requests either.u

This object is a naive implementation, suitable primarily for subclassing a useful implementation.
Powershell example
The above PowerShell example does not work

[tfl] There were rendering errors - these have been fixed and the code now works, although since the page has changed, the resutls in terms of byte size may be different from what's shown here.
Sample - converted to PowerShell
# webclient.ps1
# Web client sample recoded in PowerShell
# Converted from MSDN C# Sample
# Thomas Lee - tfl@psp.co.uk

# get a web page (author's blog)
$client = new-object system.net.WebClient
$client.Headers.Add("user-agent", "PowerShell")
$data = $client.OpenRead("http://tfl09.blogspot.com/")
$reader = new-object system.io.StreamReader $data
[string] $s = $reader.ReadToEnd()
# display output
"The returned document is {0} bytes" -f $s.length.tostring("###,###,##0")
  
# close
$data.Close()
$reader.Close()

This script produced the following output:

PSH [D:\foo]: .\webclient.ps1
The returned document is 227,213 bytes