WebClient Class

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

Namespace:  System.Net1
Assembly:  System (in System.dll)
C#
[ComVisibleAttribute(true)]
public class WebClient : 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 WebRequest2 class to provide access to resources. WebClient instances can access data with any WebRequest2 descendant registered with the WebRequest.RegisterPrefix3 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

OpenWrite4

Retrieves a Stream5 used to send data to the resource.

OpenWriteAsync6

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

UploadData7

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

UploadDataAsync9

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

UploadFile10

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

UploadFileAsync11

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

UploadValues12

Sends a NameValueCollection13 to the resource and returns a Byte8 array containing any response.

UploadValuesAsync14

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

UploadString15

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

UploadStringAsync17

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

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

Method

Description

OpenRead18

Returns the data from a resource as a Stream5.

OpenReadAsync19

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

DownloadData20

Downloads data from a resource and returns a Byte8 array.

DownloadDataAsync21

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

DownloadFile22

Downloads data from a resource to a local file.

DownloadFileAsync23

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

DownloadString24

Downloads a String16 from a resource and returns a String16.

DownloadStringAsync25

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

You can use the CancelAsync26 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 Headers27 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.

AllowAutoRedirect28 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.

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


#using <mscorlib.dll>
#using <System.dll>
using namespace System;
using namespace System::Net;
using namespace System::IO;

int main ()
{
    String* args[] = Environment::GetCommandLineArgs();

    if (args == 0 || args->Length == 1)
    {
        throw new ApplicationException (S"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 (S"user-agent", S"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");

    Stream* data = client->OpenRead (args[1]);
    StreamReader* reader = new StreamReader (data);
    String* s = reader->ReadToEnd ();
    Console::WriteLine (s);
    data->Close ();
    reader->Close ();
}


  • WebPermission29  

    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 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements33.

.NET Framework

Supported in: 3.5, 3.0, 2.0, 1.1, 1.0
Links Table
1http://msdn.microsoft.com/en-us/library/system.net(v=vs.90).aspx
2http://msdn.microsoft.com/en-us/library/system.net.webrequest(v=vs.90).aspx
3http://msdn.microsoft.com/en-us/library/system.net.webrequest.registerprefix(v=vs.90).aspx
4http://msdn.microsoft.com/en-us/library/system.net.webclient.openwrite(v=vs.90).aspx
5http://msdn.microsoft.com/en-us/library/system.io.stream(v=vs.90).aspx
6http://msdn.microsoft.com/en-us/library/system.net.webclient.openwriteasync(v=vs.90).aspx
7http://msdn.microsoft.com/en-us/library/system.net.webclient.uploaddata(v=vs.90).aspx
8http://msdn.microsoft.com/en-us/library/system.byte(v=vs.90).aspx
9http://msdn.microsoft.com/en-us/library/system.net.webclient.uploaddataasync(v=vs.90).aspx
10http://msdn.microsoft.com/en-us/library/system.net.webclient.uploadfile(v=vs.90).aspx
11http://msdn.microsoft.com/en-us/library/system.net.webclient.uploadfileasync(v=vs.90).aspx
12http://msdn.microsoft.com/en-us/library/system.net.webclient.uploadvalues(v=vs.90).aspx
13http://msdn.microsoft.com/en-us/library/system.collections.specialized.namevaluecollection(v=vs.90).aspx
14http://msdn.microsoft.com/en-us/library/system.net.webclient.uploadvaluesasync(v=vs.90).aspx
15http://msdn.microsoft.com/en-us/library/system.net.webclient.uploadstring(v=vs.90).aspx
16http://msdn.microsoft.com/en-us/library/system.string(v=vs.90).aspx
17http://msdn.microsoft.com/en-us/library/system.net.webclient.uploadstringasync(v=vs.90).aspx
18http://msdn.microsoft.com/en-us/library/system.net.webclient.openread(v=vs.90).aspx
19http://msdn.microsoft.com/en-us/library/system.net.webclient.openreadasync(v=vs.90).aspx
20http://msdn.microsoft.com/en-us/library/system.net.webclient.downloaddata(v=vs.90).aspx
21http://msdn.microsoft.com/en-us/library/system.net.webclient.downloaddataasync(v=vs.90).aspx
22http://msdn.microsoft.com/en-us/library/system.net.webclient.downloadfile(v=vs.90).aspx
23http://msdn.microsoft.com/en-us/library/system.net.webclient.downloadfileasync(v=vs.90).aspx
24http://msdn.microsoft.com/en-us/library/system.net.webclient.downloadstring(v=vs.90).aspx
25http://msdn.microsoft.com/en-us/library/system.net.webclient.downloadstringasync(v=vs.90).aspx
26http://msdn.microsoft.com/en-us/library/system.net.webclient.cancelasync(v=vs.90).aspx
27http://msdn.microsoft.com/en-us/library/system.net.webclient.headers(v=vs.90).aspx
28http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.allowautoredirect(v=vs.90).aspx
29http://msdn.microsoft.com/en-us/library/system.net.webpermission(v=vs.90).aspx
30http://msdn.microsoft.com/en-us/library/system.object(v=vs.90).aspx
31http://msdn.microsoft.com/en-us/library/system.marshalbyrefobject(v=vs.90).aspx
32http://msdn.microsoft.com/en-us/library/system.componentmodel.component(v=vs.90).aspx
33http://msdn.microsoft.com/en-us/library/8z6watww(v=vs.90).aspx
34http://msdn.microsoft.com/en-us/library/system.net.webclient_members(v=vs.90).aspx
35http://msdn.microsoft.com/en-us/library/system.net.webresponse(v=vs.90).aspx
36http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest(v=vs.90).aspx
37http://msdn.microsoft.com/en-us/library/system.net.httpwebresponse(v=vs.90).aspx
Community Content Add
Annotations FAQ
Webclient is not a member of system.net
I have a device application project and I am getting this error.

I am using VB code in Symbol terminal with WINCE 5.0 and using compact framework 2.0
It does not allow me to use webclient to download a picture from a server from http site.

There is any classe that we can use in compact netframework 2.0 and wince ?

Thanks,
WebClient vs. HttpWebRequest

What is the difference between this class and HttpWebRequest class?


[tfl - 22 10 09] Hi - and thanks for your post. You should post questions like this to the MSDN Forums at http://forums.microsoft.com/msdn or the MSDN Newsgroups at 
  http://www.microsoft.com/communities/newsgroups/en-us/. You are much more likely get a quicker response using the forums than through the Community Content. For specific help about:
Visual Studio : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.vstudio%2C&
SQL Server : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.sqlserver%2C&
.NET Framework : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.dotnet.framework
PowerShell : http://groups.google.com/group/microsoft.public.windows.powershell/topics?pli=1
All Public : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public%2C&
Also don't forget to Dispose the stream.

The example also fails to dispose the stream returned by the OpenRead method. Also, the example is sort of strange in that it employs an arbitrary UserAgent.

Here's a better example:


  using (WebClient client = new WebClient ())
{
    using (System.IO.Stream s = client.OpenRead(uri) )
{
byte[] bytes = s.ReadAllBytes();
// do your thing...
}
}



But that is a bit contrived. If you want to get all the bytes from a URI, you would use the WebClient.DownloadData() method, like so:




  using (WebClient client = new WebClient ())
{
      byte[] bytes = client.DownloadData(uri);
// do your thing...
}
}




Also be aware: The alternative contrived example code provided here employs an extension method, ReadAllBytes, on the Stream class, defined like so:


    public static class Extensions
{
/// <summary>
/// Reads the contents of the stream into a byte array.
/// data is returned as a byte array. An IOException is
/// thrown if any of the underlying IO calls fail.
/// </summary>
/// <param name="stream">The stream to read.</param>
/// <returns>A byte array containing the contents of the stream.</returns>
/// <exception cref="NotSupportedException">The stream does not support reading.</exception>
/// <exception cref="ObjectDisposedException">Methods were called after the stream was closed.</exception>
/// <exception cref="System.IO.IOException">An I/O error occurs.</exception>
public static byte[] ReadAllBytes(this System.IO.Stream source)
{
long originalPosition = 0;
if (source.CanSeek)
{
originalPosition= source.Position;
source.Position = 0;
}

try
{
byte[] readBuffer = new byte[4096];

int totalBytesRead = 0;
int bytesRead;

while ((bytesRead = source.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
{
totalBytesRead += bytesRead;

if (totalBytesRead == readBuffer.Length)
{
int nextByte = source.ReadByte();
if (nextByte != -1)
{
byte[] temp = new byte[readBuffer.Length * 2];
Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
readBuffer = temp;
totalBytesRead++;
}
}
}

byte[] buffer = readBuffer;
if (readBuffer.Length != totalBytesRead)
{
buffer = new byte[totalBytesRead];
Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead);
}
return buffer;
}
finally
{
if (source.CanSeek)
source.Position = originalPosition;
}
}
}






This extension is taken, slightly modified, from


http://www.lostechies.com/blogs/sdorman/archive/2009/01/10/reading-all-bytes-from-a-stream.aspx


Don't forget to Dispose()
The WebClient class inherits the IDisposable interface and should therefore be disposed properly. If you are using C#, then use the using statement like this:
using(WebClient client = new WebClient()) {
// Do your thing
}