10 out of 29 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 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 ();
    }
}


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


  • 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 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 Requirements.

.NET Framework

Supported in: 3.5, 3.0, 2.0, 1.1, 1.0
Did you find this helpful?
(1500 characters remaining)
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
}