WebClient Class
Provides common methods for sending data to and receiving data from a resource identified by a URI.
Assembly: System (in System.dll)
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:
|
|---|
|
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 |
|---|---|
|
Retrieves a Stream5 used to send data to the resource. |
|
|
Retrieves a Stream5 used to send data to the resource, without blocking the calling thread. |
|
|
Sends a byte array to the resource and returns a Byte8 array containing any response. |
|
|
Sends a Byte8 array to the resource, without blocking the calling thread. |
|
|
Sends a local file to the resource and returns a Byte8 array containing any response. |
|
|
Sends a local file to the resource, without blocking the calling thread. |
|
|
Sends a NameValueCollection13 to the resource and returns a Byte8 array containing any response. |
|
|
Sends a NameValueCollection13 to the resource and returns a Byte8 array containing any response, without blocking the calling thread. |
|
|
Sends a String16 to the resource, without blocking the calling thread. |
|
|
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 |
|---|---|
|
Returns the data from a resource as a Stream5. |
|
|
Returns the data from a resource, without blocking the calling thread. |
|
|
Downloads data from a resource and returns a Byte8 array. |
|
|
Downloads data from a resource and returns a Byte8 array, without blocking the calling thread. |
|
|
Downloads data from a resource to a local file. |
|
|
Downloads data from a resource to a local file, without blocking the calling thread. |
|
|
Downloads a String16 from a resource and returns a String16. |
|
|
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.
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.
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.
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,
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&
- 10/14/2009
- Robert-pl
- 10/22/2009
- Thomas Lee
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
using(WebClient client = new WebClient()) {
// Do your thing
}
- 2/4/2009
- Wictor Wilén - MVP
Note: