System.Net.WebClient Class

Assembly: System.dll
Namespace: System.Net
Summary
Provides common methods for sending data to and receiving data from a resource identified by a URI. This class cannot be inherited.
C# Syntax:
public sealed class WebClient : Component
Remarks
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 Internet resources. WebClient instances can access data with any WebRequest descendant registered with the WebRequest.RegisterPrefix method.



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

The WebClient class provides four methods for uploading data to a resource:

The WebClient class also provides three methods for downloading data from a resource:

See also:
System.Net Namespace | WebRequest | WebResponse | HttpWebRequest | HttpWebResponse

System.Net.WebClient Member List:

Public Constructors
ctor #1 Default constructor. This constructor is called by derived class constructors to initialize state in this type.
Initializes a new instance of the WebClient class.
Public Properties
BaseAddress Read-write

Gets or sets the base URI for requests made by a WebClient.
Container
(inherited from System.ComponentModel.Component)
Read-only

See base class member description: System.ComponentModel.Component.Container


Gets the IContainer that contains the Component.
Credentials Read-write

Gets or sets the network credentials used to authenticate the request with the Internet resource.
Headers Read-write

Gets or sets a collection of header name/value pairs associated with the request.
QueryString Read-write

Gets or sets a collection of query name/value pairs associated with the request.
ResponseHeaders Read-only

Gets a collection of header name/value pairs associated with the response.
Site
(inherited from System.ComponentModel.Component)
Read-write

See base class member description: System.ComponentModel.Component.Site


Gets or sets the ISite of the Component.
Public Methods
CreateObjRef
(inherited from System.MarshalByRefObject)
See base class member description: System.MarshalByRefObject.CreateObjRef


Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
Dispose
(inherited from System.ComponentModel.Component)
Overloaded:
Dispose()

See base class member description: System.ComponentModel.Component.Dispose


Releases all resources used by the Component.
DownloadData Downloads data from a resource with the specified URI.
DownloadFile Downloads data from a resource with the specified URI to a local file.
Equals
(inherited from System.Object)
See base class member description: System.Object.Equals

Derived from System.Object, the primary base class for all objects.
GetHashCode
(inherited from System.Object)
See base class member description: System.Object.GetHashCode

Derived from System.Object, the primary base class for all objects.
GetLifetimeService
(inherited from System.MarshalByRefObject)
See base class member description: System.MarshalByRefObject.GetLifetimeService


Retrieves the current lifetime service object that controls the lifetime policy for this instance.
GetType
(inherited from System.Object)
See base class member description: System.Object.GetType

Derived from System.Object, the primary base class for all objects.
InitializeLifetimeService
(inherited from System.MarshalByRefObject)
See base class member description: System.MarshalByRefObject.InitializeLifetimeService


Obtains a lifetime service object to control the lifetime policy for this instance.
OpenRead Opens a readable stream for the data downloaded from a resource with the specified URI.
OpenWrite Overloaded:
OpenWrite(string address)

Opens a stream for writing data to the specified resource.
OpenWrite Overloaded:
OpenWrite(string address, string method)

Opens a stream for writing data to the specified resource with using the specified method.
ToString
(inherited from System.Object)
See base class member description: System.Object.ToString

Derived from System.Object, the primary base class for all objects.
UploadData Overloaded:
UploadData(string address, byte[] data)

Uploads a data buffer to a resource identified by a URI.
UploadData Overloaded:
UploadData(string address, string method, byte[] data)

Uploads a data buffer to the specified resource using the specified method.
UploadFile Overloaded:
UploadFile(string address, string fileName)

Uploads the specified local file to a resource with the specified URI.
UploadFile Overloaded:
UploadFile(string address, string method, string fileName)

Uploads the specified local file to the specified resource using the specified method.
UploadValues Overloaded:
UploadValues(string address, NameValueCollection data)

Uploads the specified name/value collection to the specified resource identified by a URI.
UploadValues Overloaded:
UploadValues(string address, string method, NameValueCollection data)

Uploads the specified name/value collection to the specified resource with the specified URI using the specified method.
Public Events
Disposed
(inherited from System.ComponentModel.Component)
See base class member description: System.ComponentModel.Component.Disposed


Adds an event handler to listen to the Component.Disposed event on the component.
Protected Properties
DesignMode
(inherited from System.ComponentModel.Component)
Read-only

See base class member description: System.ComponentModel.Component.DesignMode


Gets a value that indicates whether the Component is currently in design mode.
Events
(inherited from System.ComponentModel.Component)
Read-only

See base class member description: System.ComponentModel.Component.Events


Gets the list of event handlers that are attached to this Component.
Protected Methods
Dispose
(inherited from System.ComponentModel.Component)
Overloaded:
Dispose(bool disposing)

See base class member description: System.ComponentModel.Component.Dispose


Releases the unmanaged resources used by the Component and optionally releases the managed resources.
Finalize
(inherited from System.Object)
See base class member description: System.Object.Finalize

Derived from System.Object, the primary base class for all objects.
GetService
(inherited from System.ComponentModel.Component)
See base class member description: System.ComponentModel.Component.GetService


Returns an object that represents a service provided by the Component or by its Container.
MemberwiseClone
(inherited from System.Object)
See base class member description: System.Object.MemberwiseClone

Derived from System.Object, the primary base class for all objects.

Hierarchy:


System.Net.WebClient Member Details

ctor #1
Summary
Initializes a new instance of the WebClient class.

Default constructor. This constructor is called by derived class constructors to initialize state in this type.
C# Syntax:
public WebClient();
Remarks
The default constructor creates a new instance of the WebClient class with each field set to null.
Example
The following example creates a WebClient instance and then uses it to download data from a server and display it on the system console, to download data from a server and write it to a file, and to upload form values to a server and receive the response.
        try {
			
		// Download the data to a buffer.
	       	WebClient client = new WebClient();

  		Byte[] pageData = client.DownloadData("http://www.contoso.com");
		string pageHtml = Encoding.ASCII.GetString(pageData);
		Console.WriteLine(pageHtml);

		// Download the data to a file.
	        	client.DownloadFile("http://www.contoso.com", "page.htm");

		// Upload some form post values.
		NameValueCollection form = new NameValueCollection();		
		form.Add("MyName", "MyValue");		
		Byte[] responseData = client.UploadValues("http://www.contoso.com/form.aspx", form);		

        }
        catch (WebException webEx) {
          	Console.WriteLine(webEx.ToString());
           	if(webEx.Status == WebExceptionStatus.ConnectFailure) {
           		Console.WriteLine("Are you behind a firewall?  If so, go through the proxy server.");
           	}
        }

    

Return to top


Property: BaseAddress (read-write)
Summary
Gets or sets the base URI for requests made by a WebClient.
C# Syntax:
public string BaseAddress {get; set;}
Exceptions
Exception Type Condition
ArgumentException WebClient.BaseAddress is set to an invalid URI.
Remarks
The WebClient.BaseAddress property contains a base URI that is combined with the relative address specified when calling an upload or download method.

If the WebClient.BaseAddress property is set, the URI specified when calling the following methods must be a relative URI:

Example
The following example downloads data from an Internet server and displays it on the console. It assumes that the server's address (such as http://www.contoso.com) is in hostUri and that the path to the resource (such as /default.htm) is in uriSuffix .
			// Create a new WebClient instance.
			WebClient myWebClient = new WebClient();

			// Set the BaseAddress of the Web Resource in the WebClient.
			myWebClient.BaseAddress = hostUri;
			Console.WriteLine("Downloading from " + hostUri + "/" + uriSuffix);
			Console.WriteLine("\nPress Enter key to continue");
			Console.ReadLine();	
	
			// Download the target Web Resource into a byte array.
			byte[] myDatabuffer = myWebClient.DownloadData (uriSuffix);

			// Display the downloaded data.
			string download = Encoding.ASCII.GetString(myDatabuffer);
			Console.WriteLine(download);
			
			Console.WriteLine("Download of " + myWebClient.BaseAddress.ToString() + uriSuffix + " was successful.");

    

Return to top


Property: Container (read-only)
Inherited
See base class member description: System.ComponentModel.Component.Container

Summary
Gets the IContainer that contains the Component.
C# Syntax:
public IContainer Container {get;}
Remarks
The components in a container are tracked in a first-in, first-out list, which also defines the order of the components within the container. The last component added is the last component in the list.
See also:
IContainer | Container

Return to top


Property: Credentials (read-write)
Summary
Gets or sets the network credentials used to authenticate the request with the Internet resource.
C# Syntax:
public ICredentials Credentials {get; set;}
Remarks
The WebClient.Credentials property contains the authentication credentials required to access the Internet resource.
Example
The following example uses the user's system credentials to authenticate a request.
	public static void Main()
	{           
		try {

			WebClient client = new WebClient();

  			client.Credentials = CredentialCache.DefaultCredentials;
	
			Byte[] pageData = client.DownloadData("http://www.contoso.com");
			string pageHtml = Encoding.ASCII.GetString(pageData);
			Console.WriteLine(pageHtml);

		} catch (WebException webEx) {
			Console.Write(webEx.ToString());
		}
	}    

    
See also:
NetworkCredential | CredentialCache | WebRequest.Credentials

Return to top


Property: DesignMode (read-only)
Inherited
See base class member description: System.ComponentModel.Component.DesignMode

Summary
Gets a value that indicates whether the Component is currently in design mode.
C# Syntax:
protected bool DesignMode {get;}
Remarks
The design mode indicator is stored in the ISite; therefore, if the Component does not have an ISite associated with it, this property is always false.
See also:
IContainer | Container | ISite

Return to top


Property: Events (read-only)
Inherited
See base class member description: System.ComponentModel.Component.Events

Summary
Gets the list of event handlers that are attached to this Component.
C# Syntax:
protected EventHandlerList Events {get;}
Remarks
For more information about handling events, see the conceptual topic at MSDN: eventsoverview.
See also:
EventHandlerList

Return to top


Property: Headers (read-write)
Summary
Gets or sets a collection of header name/value pairs associated with the request.
C# Syntax:
public WebHeaderCollection Headers {get; set;}
Remarks
The WebClient.Headers property contains a WebHeaderCollection instance containing header informationthat the WebClient sends to the Internet resource. This is an unrestricted collection of headers, so setting headers that are restricted by WebRequest descendants such as HttpWebRequest is allowed.
Example
The following example uses the WebClient.Headers collection to set the HTTP Content-Type header to "application/x-www-form-urlencoded" to notify the server that form data is attached to the post.
			string uriString;
			Console.Write("\nPlease enter the URI to post data to {for example, http://www.contoso.com} : ");
			uriString = Console.ReadLine();
			// Create a new WebClient instance.
			WebClient myWebClient = new WebClient();
			Console.WriteLine("\nPlease enter the data to be posted to the URI {0}:",uriString);
			string postData = Console.ReadLine();
			myWebClient.Headers.Add("Content-Type","application/x-www-form-urlencoded");
			// Apply ASCII Encoding to obtain the string as a byte array.
			byte[] byteArray = Encoding.ASCII.GetBytes(postData);
			Console.WriteLine("Uploading to {0} ...",  uriString);						
			// Upload the input string using the HTTP 1.0 POST method.
			byte[] responseArray = myWebClient.UploadData(uriString,"POST",byteArray);
			// Decode and display the response.
			Console.WriteLine("\nResponse received was {0}",
				Encoding.ASCII.GetString(responseArray));

    
See also:
WebRequest.Headers | HttpWebRequest.Headers

Return to top


Property: QueryString (read-write)
Summary
Gets or sets a collection of query name/value pairs associated with the request.
C# Syntax:
public NameValueCollection QueryString {get; set;}
Remarks
The WebClient.QueryString property contains a NameValueCollection instance containing name/value pairs that are appended to the URI as a query string. The contents of the WebClient.QueryString property are preceded by a question mark (?), and name/value pairs are separated from one another by an ampersand (&).
Example
The following example takes user input from the command line and builds a NameValueCollection that is assigned to the WebClient.QueryString property. It then downloads the response from the server to a local file.
			string uriString = "http://www.contoso.com/search";
			// Create a new WebClient instance.
			WebClient myWebClient = new WebClient();
			// Create a new NameValueCollection instance to hold the QueryString parameters and values.
			NameValueCollection myQueryStringCollection = new NameValueCollection();
			Console.Write("Enter the word(s), separated by space character to search for in " +  uriString + ": ");
			// Read user input phrase to search for at uriString.
			string searchPhrase = Console.ReadLine();
			if (searchPhrase.Length > 1)
				// Assign the user-defined search phrase.
				myQueryStringCollection.Add("q",searchPhrase);
			else
				// If error, default to search for 'Microsoft'.
				myQueryStringCollection.Add("q","Microsoft");		
			// Assign auxilliary parameters required for the search.
			Console.WriteLine("Searching " + uriString + " .......");
			// Attach QueryString to the WebClient.
			myWebClient.QueryString = myQueryStringCollection;
			// Download the search results Web page into 'searchresult.htm' for inspection.
			myWebClient.DownloadFile (uriString, "searchresult.htm");
			Console.WriteLine("\nDownload of " + uriString + " was successful. Please see 'searchresult.htm' for results.");

    

Return to top


Property: ResponseHeaders (read-only)
Summary
Gets a collection of header name/value pairs associated with the response.
C# Syntax:
public WebHeaderCollection ResponseHeaders {get;}
Remarks
The WebClient.ResponseHeaders property contains a WebHeaderCollection instance containing header information the WebClient receives from the Internet resource.
Example
The following example downloads and displays the WebClient.ResponseHeaders returned by a server.
			// Obtain the WebHeaderCollection instance containing the header name/value pair from the response.
			WebHeaderCollection myWebHeaderCollection = myWebClient.ResponseHeaders;
			Console.WriteLine("\nDisplaying the response headers\n");
			// Loop through the ResponseHeaders and display the header name/value pairs.
			for (int i=0; i < myWebHeaderCollection.Count; i++)				
				Console.WriteLine ("\t" + myWebHeaderCollection.GetKey(i) + " = " + myWebHeaderCollection.Get(i));

    

Return to top


Property: Site (read-write)
Inherited
See base class member description: System.ComponentModel.Component.Site

Summary
Gets or sets the ISite of the Component.
C# Syntax:
public virtual ISite Site {get; set;}
Implements:
IComponent.Site
Remarks
A Component will have an ISite if it has been added to an IContainer and the IContainer assigns an ISite to it. The IContainer is responsible to assign the ISite to the Component. Changing the value of the component's ISite does not necessarily change the name of the site the Component is assigned to. It is strongly suggested that the setting of the Component.Site property only be done by an IContainer.

The property value is null if the Component is removed from its IContainer. Assigning null to this property does not necessarily remove the Component from the IContainer.

A Component might or might not have a name. If a Component is given a name, the name must be unique among other Component objects within its IContainer. The ISite stores the name of the Component; therefore, you can only name a Component if it has an ISite associated with it.

See also:
IContainer | Container | ISite

Return to top


Method: CreateObjRef(
   Type requestedType
)
Inherited
See base class member description: System.MarshalByRefObject.CreateObjRef

Summary
Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
C# Syntax:
public virtual ObjRef CreateObjRef(
   Type requestedType
);
Parameters:

requestedType

The Type of the object that the new ObjRef will reference.

Return Value:
Information required to generate a proxy.
Exceptions
Exception Type Condition
RemotingException This instance is not a valid remoting object.

Return to top


Overloaded Method: Dispose()
Inherited
See base class member description: System.ComponentModel.Component.Dispose

Summary
Releases all resources used by the Component.
C# Syntax:
public void Dispose();
Implements:
IDisposable.Dispose
Remarks
Calling Component.Dispose allows the resources used by the Component to be reallocated for other purposes. For more information about Component.Dispose, see the conceptual topic at MSDN: cleaningupunmanagedresources.
See also:
IContainer | Container

Return to top


Overloaded Method: Dispose(
   bool disposing
)
Inherited
See base class member description: System.ComponentModel.Component.Dispose

Summary
Releases the unmanaged resources used by the Component and optionally releases the managed resources.
C# Syntax:
protected virtual void Dispose(
   bool disposing
);
Parameters:

disposing

true to release both managed and unmanaged resources; false to release only unmanaged resources.

Remarks
This method is called by the public Dispose method and the Object.Finalize method.Dispose() invokes the protected Dispose(Boolean) method with the disposing parameter set to true. Object.Finalize invokes Dispose with disposing set to false.

When the disposing parameter is true, this method releases all resources held by any managed objects that this Component references. This method invokes the Dispose() method of each referenced object.



Notes to inheritors: Dispose can be called multiple times by other objects. When overriding Dispose(Boolean), be careful not to reference objects that have been previously disposed of in an earlier call to Dispose. For more information about how to implement Dispose(Boolean), see the conceptual topic at MSDN: implementingdisposemethod.

For more information about Dispose and Object.Finalize, see the conceptual topic at MSDN: cleaningupunmanagedresources and the conceptual topic at MSDN: overridingfinalizemethod.

Return to top


Method: DownloadData(
   string address
)
Summary
Downloads data from a resource with the specified URI.
C# Syntax:
public byte[] DownloadData(
   string address
);
Parameters:

address

The URI to download data from.

Return Value:
A byte array containing the data downloaded from the resource specified in the address parameter.
Exceptions
Exception Type Condition
WebException An error occurs while downloading data.
UriFormatException The URI formed by combining WebClient.BaseAddress, address, and WebClient.QueryString is invalid.
Remarks
The WebClient.DownloadData method downloads the data from the URI specified by the address parameter to a local byte array.

If the WebClient.BaseAddress property is not empty, address must be a relative URI that is combined with WebClient.BaseAddress to form the absolute URI of the requested data. If the WebClient.QueryString property is not empty, it is appended to address.

Example
The following example requests data from a server and displays the data returned. It assumes that remoteUri contains a valid URI for the requested data.
			// Create a new WebClient instance.
			WebClient myWebClient = new WebClient();
			// Download home page data.
			Console.WriteLine("Downloading " + remoteUri);						
			// Download the Web resource and save it into a data buffer.
			byte[] myDataBuffer = myWebClient.DownloadData (remoteUri);

			// Display the downloaded data.
			string download = Encoding.ASCII.GetString(myDataBuffer);
			Console.WriteLine(download);
								
			Console.WriteLine("Download successful.");

    

Return to top


Method: DownloadFile(
   string address,
   string fileName
)
Summary
Downloads data from a resource with the specified URI to a local file.
C# Syntax:
public void DownloadFile(
   string address,
   string fileName
);
Parameters:

address

The URI to download data from.

fileName

The name of the local file to receive the data.

Exceptions
Exception Type Condition
WebException An error occurs while downloading data.
UriFormatException The URI formed by combining WebClient.BaseAddress, address, and WebClient.QueryString is invalid.
Remarks
The WebClient.DownloadFile method downloads data from the URI specified by in the address parameter to a local file.

If the WebClient.BaseAddress property is not empty, address must be a relative URI that is combined with WebClient.BaseAddress to form the absolute URI of the requested data. If the WebClient.QueryString property is not empty, it is appended to address.

Example
The following example downloads a file from http://www.contoso.com to the local hard drive.
			string remoteUri = "http://www.contoso.com/library/homepage/images/";
			string fileName = "ms-banner.gif", myStringWebResource = null;
			// Create a new WebClient instance.
			WebClient myWebClient = new WebClient();
			// Concatenate the domain with the Web resource filename.
			myStringWebResource = remoteUri + fileName;
			Console.WriteLine("Downloading File \"{0}\" from \"{1}\" .......\n\n", fileName, myStringWebResource);
			// Download the Web resource and save it into the current filesystem folder.
			myWebClient.DownloadFile(myStringWebResource,fileName);		
			Console.WriteLine("Successfully Downloaded File \"{0}\" from \"{1}\"", fileName, myStringWebResource);
			Console.WriteLine("\nDownloaded file saved in the following file system folder:\n\t" + Application.StartupPath.);

    

Return to top


Method: Equals(
   object obj
)
Inherited
See base class member description: System.Object.Equals
C# Syntax:
public virtual bool Equals(
   object obj
);

For more information on members inherited from System.Object click on the link above.

Return to top


Method: Finalize()
Inherited
See base class member description: System.Object.Finalize
C# Syntax:
~WebClient();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: GetHashCode()
Inherited
See base class member description: System.Object.GetHashCode
C# Syntax:
public virtual int GetHashCode();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: GetLifetimeService()
Inherited
See base class member description: System.MarshalByRefObject.GetLifetimeService

Summary
Retrieves the current lifetime service object that controls the lifetime policy for this instance.
C# Syntax:
public object GetLifetimeService();
Return Value:
An object of type ILease used to control the lifetime policy for this instance.
Remarks
For more information about lifetime services, see the LifetimeServices class.

Return to top


Method: GetService(
   Type service
)
Inherited
See base class member description: System.ComponentModel.Component.GetService

Summary
Returns an object that represents a service provided by the Component or by its Container.
C# Syntax:
protected virtual object GetService(
   Type service
);
Parameters:

service

A service provided by the Component.

Return Value:
An Object that represents a service provided by the Component.

This value is null if the Component does not provide the specified service.

Remarks
This method can be overridden by a derived class.
See also:
IContainer | Container | ISite | IServiceProvider

Return to top


Method: GetType()
Inherited
See base class member description: System.Object.GetType
C# Syntax:
public Type GetType();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: InitializeLifetimeService()
Inherited
See base class member description: System.MarshalByRefObject.InitializeLifetimeService

Summary
Obtains a lifetime service object to control the lifetime policy for this instance.
C# Syntax:
public virtual object InitializeLifetimeService();
Return Value:
An object of type ILease used to control the lifetime policy for this instance. This is the current lifetime service object for this instance if one exists; otherwise, a new lifetime service object initialized to the value of the LifetimeServices.LeaseManagerPollTime property.
Remarks
For more information about lifetime services, see the LifetimeServices class.
Example
The following code example demonstrates creating a lease.
 public class MyClass : MarshalByRefObject
 {
   public override Object InitializeLifetimeService()
   {
     ILease lease = (ILease)base.InitializeLifetimeService();
     if (lease.CurrentState == LeaseState.Initial)
     {
          lease.InitialLeaseTime = TimeSpan.FromMinutes(1);
          lease.SponsorshipTimeout = TimeSpan.FromMinutes(2);
           lease.RenewOnCallTime = TimeSpan.FromSeconds(2);
     }
       return lease;
   }
 }

    

Return to top


Method: MemberwiseClone()
Inherited
See base class member description: System.Object.MemberwiseClone
C# Syntax:
protected object MemberwiseClone();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: OpenRead(
   string address
)
Summary
Opens a readable stream for the data downloaded from a resource with the specified URI.
C# Syntax:
public Stream OpenRead(
   string address
);
Parameters:

address

The URI to download data from.

Return Value:
A Stream used to read data from a resource.
Exceptions
Exception Type Condition
WebException An error occurs while downloading data.
UriFormatException The URI formed by combining WebClient.BaseAddress, address, and WebClient.QueryString is invalid.
Remarks
The WebClient.OpenRead method creates a Stream instance used to access the data specified by the address parameter.

If the WebClient.BaseAddress property is not empty, address must be a relative URI that is combined with WebClient.BaseAddress to form the absolute URI of the requested data. If the WebClient.QueryString property is not null, it is appended to address.



Note You must call Stream.Close when finished with the Stream to avoid running out of system resources.
Example
The following example opens the resource identified by uriString and displays the results on the system console. Note that the Stream returned by WebClient.OpenRead is closed when the data has been read.
			// Create a new WebClient instance.
			WebClient myWebClient = new WebClient();
			// Download home page data. 
			Console.WriteLine("Accessing {0} ...",  uriString);						
			// Open a stream to point to the data stream coming from the Web resource.
			Stream myStream = myWebClient.OpenRead(uriString);

			Console.WriteLine("\nDisplaying Data :\n");
			StreamReader sr = new StreamReader(myStream);
			Console.WriteLine(sr.ReadToEnd());


			// Close the stream. 
			myStream.Close();

    

Return to top


Overloaded Method: OpenWrite(
   string address
)
Summary
Opens a stream for writing data to the specified resource.
C# Syntax:
public Stream OpenWrite(
   string address
);
Parameters:

address

The URI of the resource to receive the data.

Return Value:
A Stream used to write data to the resource.
Exceptions
Exception Type Condition
WebException An error occurs while opening the stream.
UriFormatException The URI formed by combining WebClient.BaseAddress, address, and WebClient.QueryString is invalid.
Remarks
The WebClient.OpenWrite method returns a writable stream that is used to send data to a resource. The underlying request is made with the POST method.

If the WebClient.BaseAddress property is not empty, address must be a relative URI that is combined with WebClient.BaseAddress to form the absolute URI of the requested data. If the WebClient.QueryString property is not empty, it is appended to address.

Example
The following example reads data from the command line and uses WebClient.OpenWrite to obtain a stream for writing the data. Note that the Stream returned by WebClient.OpenWrite is closed after the data is sent.
			string uriString;
			Console.Write("\nPlease enter the URI to post data to : ");
			uriString = Console.ReadLine();
			Console.WriteLine("\nPlease enter the data to be posted to the URI {0}:",uriString);
			string postData = Console.ReadLine();
			// Apply Ascii Encoding to obtain an array of bytes. 
			byte[] postArray = Encoding.ASCII.GetBytes(postData);

			// Create a new WebClient instance.
			WebClient myWebClient = new WebClient();

			// postStream implicitly sets HTTP POST as the request method.
			Console.WriteLine("Uploading to {0} ...",  uriString);							Stream postStream = myWebClient.OpenWrite(uriString);

			postStream.Write(postArray,0,postArray.Length);

			// Close the stream and release resources.
			postStream.Close();

			Console.WriteLine("\nSuccessfully posted the data.");

    

Return to top


Overloaded Method: OpenWrite(
   string address,
   string method
)
Summary
Opens a stream for writing data to the specified resource with using the specified method.
C# Syntax:
public Stream OpenWrite(
   string address,
   string method
);
Parameters:

address

The URI of the resource to receive the data.

method

The method used to send the data to the resource.

Return Value:
A Stream used to write data to the resource.
Exceptions
Exception Type Condition
WebException An error occurs while opening the stream.
UriFormatException The URI formed by combining WebClient.BaseAddress, address, and WebClient.QueryString is invalid.
Remarks
The WebClient.OpenWrite method returns a writable stream that is used to send data to a resource. The underlying request is made with the method specified in the method parameter.

If the method parameter specifies a method that is not understood by the server, the underlying protocol classes determine what occurs. Typically, a WebException is thrown with the WebException.Status property set to indicate the error.

If the WebClient.BaseAddress property is not empty, address must be a relative URI that is combined with WebClient.BaseAddress to form the absolute URI of the requested data. If the WebClient.QueryString property is not empty, it is appended to address.

Example
The following example reads data from the command line and uses WebClient.OpenWrite to obtain a stream used to write the data. Note that the Stream returned by WebClient.OpenWrite is closed after the data is sent.
			string uriString;
			Console.Write("\nPlease enter the URI to post data to : ");
			uriString = Console.ReadLine();
			Console.WriteLine("\nPlease enter the data to be posted to the URI {0}:",uriString);
			string postData = Console.ReadLine();
			// Apply ASCII encoding to obtain an array of bytes .
			byte[] postArray = Encoding.ASCII.GetBytes(postData);

			// Create a new WebClient instance.
			WebClient myWebClient = new WebClient();

			Console.WriteLine("Uploading to {0} ...",  uriString);						
			Stream postStream = myWebClient.OpenWrite(uriString,"POST");
			postStream.Write(postArray,0,postArray.Length);

			// Close the stream and release resources.
			postStream.Close();
			Console.WriteLine("\nSuccessfully posted the data.");

    

Return to top


Method: ToString()
Inherited
See base class member description: System.Object.ToString
C# Syntax:
public virtual string ToString();

For more information on members inherited from System.Object click on the link above.

Return to top


Overloaded Method: UploadData(
   string address,
   byte[] data
)
Summary
Uploads a data buffer to a resource identified by a URI.
C# Syntax:
public byte[] UploadData(
   string address,
   byte[] data
);
Parameters:

address

The URI of the resource to receive the data.

data

The data buffer to send to the resource.

Return Value:
An array of bytes containing the body of any response from the resource.
Exceptions
Exception Type Condition
WebException An error occurs while opening the stream.
UriFormatException The URI formed by combining WebClient.BaseAddress, address, and WebClient.QueryString is invalid.
Remarks
The WebClient.UploadData method sends a data buffer to a resource. The underlying request is made using the POST method verb.

The POST verb is defined by HTTP. If the underlying request does not use HTTP and POST is not understood by the server, the underlying protocol classes determine what occurs. Typically, a WebException is thrown with the WebException.Status property set to indicate the error.

The WebClient.UploadData method sends the content of data to the server without encoding it.

If the WebClient.BaseAddress property is not empty, address must be a relative URI that is combined with WebClient.BaseAddress to form the absolute URI of the requested data. If the WebClient.QueryString property is not empty, it is appended to address.

Example
The following example converts a string entered from the console to a byte array and posts the array to the specified server using WebClient.UploadData. Any response from the server is displayed to the console.
			Console.Write("\nPlease enter the URI to post data to : ");
			string uriString = Console.ReadLine();
			// Create a new WebClient instance.
			WebClient myWebClient = new WebClient();
			Console.WriteLine("\nPlease enter the data to be posted to the URI {0}:",uriString);
			string postData = Console.ReadLine();
			// Apply ASCII Encoding to obtain the string as a byte array.
			byte[] postArray = Encoding.ASCII.GetBytes(postData);
			Console.WriteLine("Uploading to {0} ...",  uriString);							
         myWebClient.Headers.Add("Content-Type","application/x-www-form-urlencoded");
		
			//UploadData implicitly sets HTTP POST as the request method.
			byte[] responseArray = myWebClient.UploadData(uriString,postArray);

			// Decode and display the response.
			Console.WriteLine("\nResponse received was :{0}", Encoding.ASCII.GetString(responseArray));

    

Return to top


Overloaded Method: UploadData(
   string address,
   string method,
   byte[] data
)
Summary
Uploads a data buffer to the specified resource using the specified method.
C# Syntax:
public byte[] UploadData(
   string address,
   string method,
   byte[] data
);
Parameters:

address

The URI of the resource to receive the data.

method

The method verb used to send the data to the resource.

data

The data buffer to send to the resource.

Return Value:
An array of bytes containing the body of any response from the resource.
Exceptions
Exception Type Condition
WebException An error occurs while opening the stream.
UriFormatException The URI formed by combining WebClient.BaseAddress, address, and WebClient.QueryString is invalid.
Remarks
The WebClient.UploadData method sends a data buffer to a resource using the method verb specified in the method parameter and returns any response from the server.

The WebClient.UploadData method sends the content of data to the server without encoding it.

If the method parameter specifies a verb that is not understood by the server, the underlying protocol classes determine what occurs. Typically, a WebException is thrown with the WebException.Status property set to indicate the error.

If the WebClient.BaseAddress property is not empty, address must be a relative URI that is combined with WebClient.BaseAddress to form the absolute URI of the requested data. If the WebClient.QueryString property is not empty, it is appended to address.

Example
The following example converts a string entered from the console into a byte array and posts the array to the specified server using WebClient.UploadData. Any response from the server is displayed to the console.
			string uriString;
			Console.Write("\nPlease enter the URI to post data to {for example, http://www.contoso.com} : ");
			uriString = Console.ReadLine();
			// Create a new WebClient instance.
			WebClient myWebClient = new WebClient();
			Console.WriteLine("\nPlease enter the data to be posted to the URI {0}:",uriString);
			string postData = Console.ReadLine();
			myWebClient.Headers.Add("Content-Type","application/x-www-form-urlencoded");
			// Apply ASCII Encoding to obtain the string as a byte array.
			byte[] byteArray = Encoding.ASCII.GetBytes(postData);
			Console.WriteLine("Uploading to {0} ...",  uriString);						
			// Upload the input string using the HTTP 1.0 POST method.
			byte[] responseArray = myWebClient.UploadData(uriString,"POST",byteArray);
			// Decode and display the response.
			Console.WriteLine("\nResponse received was {0}",
				Encoding.ASCII.GetString(responseArray));

    

Return to top


Overloaded Method: UploadFile(
   string address,
   string fileName
)
Summary
Uploads the specified local file to a resource with the specified URI.
C# Syntax:
public byte[] UploadFile(
   string address,
   string fileName
);
Parameters:

address

The URI of the resource to receive the file.

fileName

The file to send to the resource.

Return Value:
An array of bytes containing the body of any response from the resource.
Exceptions
Exception Type Condition
WebException An error occurs while opening the stream.

-or-

The Content-type header begins with "multipart".

UriFormatException The URI formed by combining WebClient.BaseAddress, address, and WebClient.QueryString is invalid.
Remarks
The WebClient.UploadFile method sends a local file to a resource. The underlying request is made using the POST method verb.

The POST verb is defined by HTTP. If the underlying request does not use HTTP and POST is not understood by the server, the underlying protocol classes determine what occurs. Typically, a WebException is thrown with the WebException.Status property set to indicate the error.

If the WebClient.BaseAddress property is not empty, address must be a relative URI that is combined with WebClient.BaseAddress to form the absolute URI of the requested data. If the WebClient.QueryString property is not empty, it is appended to address.

Example
The following example uploads the specified file to the specified URI using WebClient.UploadFile. Any response returned by the server is displayed on the console.
			Console.Write("\nPlease enter the URI to post data to : ");
			String uriString = Console.ReadLine();

			// Create a new WebClient instance.
			WebClient myWebClient = new WebClient();

			Console.WriteLine("\nPlease enter the fully qualified path of the file to be uploaded to the URI");
			string fileName = Console.ReadLine();
			Console.WriteLine("Uploading {0} to {1} ...",fileName,uriString);						
			// Upload the file to the URI.
         // The 'UploadFile(uriString,fileName)' method implicitly uses HTTP POST method.
			byte[] responseArray = myWebClient.UploadFile(uriString,fileName);

			// Decode and display the response.
			Console.WriteLine("\nResponse Received.The contents of the file uploaded are: \n{0}",Encoding.ASCII.GetString(responseArray));

    

Return to top


Overloaded Method: UploadFile(
   string address,
   string method,
   string fileName
)
Summary
Uploads the specified local file to the specified resource using the specified method.
C# Syntax:
public byte[] UploadFile(
   string address,
   string method,
   string fileName
);
Parameters:

address

The URI of the resource to receive the file.

method

The method verb used to send the file to the resource.

fileName

The file to send to the resource.

Return Value:
An array of bytes containing the body of any response from the resource.
Exceptions
Exception Type Condition
WebException An error occurs while opening the stream.

-or-

The Content-type header begins with "multipart".

UriFormatException The URI formed by combining WebClient.BaseAddress, address, and WebClient.QueryString is invalid.
Remarks
The WebClient.UploadFile method sends a local file to a resource using the method verb specified in the method parameter and returns any response from the server.

If the method parameter specifies a verb that is not understood by the server, the underlying protocol classes determine what occurs. Typically, a WebException is thrown with the WebException.Status property set to indicate the error.

If the WebClient.BaseAddress property is not empty, address must be a relative URI that is combined with WebClient.BaseAddress to form the absolute URI of the requested data. If the WebClient.QueryString property is not empty, it is appended to address.

Example
The following example uploads the specified file to the specified URI using WebClient.UploadFile. Any response returned by the server is displayed on the console.
			Console.Write("\nPlease enter the URL to post data to : ");
			String uriString = Console.ReadLine();

			// Create a new WebClient instance.
			WebClient myWebClient = new WebClient();

			Console.WriteLine("\nPlease enter the fully qualified path of the file to be uploaded to the URL");
			string fileName = Console.ReadLine();

			Console.WriteLine("Uploading {0} to {1} ...",fileName,uriString);						
			// Upload the file to the URL using the HTTP 1.0 POST.
			byte[] responseArray = myWebClient.UploadFile(uriString,"POST",fileName);

			// Decode and display the response.
			Console.WriteLine("\nResponse Received.The contents of the file uploaded are: \n{0}",Encoding.ASCII.GetString(responseArray));

    

Return to top


Overloaded Method: UploadValues(
   string address,
   NameValueCollection data
)
Summary
Uploads the specified name/value collection to the specified resource identified by a URI.
C# Syntax:
public byte[] UploadValues(
   string address,
   NameValueCollection data
);
Parameters:

address

The URI of the resource to receive the collection.

data

The NameValueCollection to send to the resource.

Return Value:
An array of bytes containing the body of any response from the resource.
Exceptions
Exception Type Condition
WebException An error occurs while opening the stream.

-or-

The Content-type header is not "application/x-www-form-urlencoded".

UriFormatException The URI formed by combining WebClient.BaseAddress, address, and WebClient.QueryString is invalid.
Remarks
The WebClient.UploadValues method sends a NameValueCollection to an Internet server. The underlying request is made using the POST method verb.

The POST verb is defined by HTTP. If the underlying request does not use HTTP and POST is not understood by the server, the underlying protocol classes determine what occurs. Typically, a WebException is thrown with the WebException.Status property set to indicate the error.

The WebClient.UploadValues method always sets the Content-type header to "Content-type: application/x-www-form-urlencoded".

If the WebClient.BaseAddress property is not empty, address must be a relative URI that is combined with WebClient.BaseAddress to form the absolute URI of the requested data. If the WebClient.QueryString property is not empty, it is appended to address.

Example
The following example gathers information from the user (name, age, and address) and posts the values to the server using WebClient.UploadValues. Any response from the server is displayed on the console.
			Console.Write("\nPlease enter the URI to post data to : ");
			string uriString = Console.ReadLine();

			// Create a new WebClient instance.
			WebClient myWebClient = new WebClient();

			// Create a new NameValueCollection instance to hold some custom parameters to be posted to the URL.
			NameValueCollection myNameValueCollection = new NameValueCollection();
			
			Console.WriteLine("Please enter the following parameters to be posted to the URL");
			Console.Write("Name:");
			string name = Console.ReadLine();

			Console.Write("Age:");
			string age = Console.ReadLine();

			Console.Write("Address:");
			string address = Console.ReadLine();

			// Add necessary parameter/value pairs to the name/value container.
			myNameValueCollection.Add("Name",name);			
			myNameValueCollection.Add("Address",address);
			myNameValueCollection.Add("Age",age);

			Console.WriteLine("\nUploading to {0} ...",  uriString);
			// 'The Upload(String,NameValueCollection)' implicitly method sets HTTP POST as the request method.			
			byte[] responseArray = myWebClient.UploadValues(uriString,myNameValueCollection);
			
			// Decode and display the response.
			Console.WriteLine("\nResponse received was :\n{0}",Encoding.ASCII.GetString(responseArray));

    

Return to top


Overloaded Method: UploadValues(
   string address,
   string method,
   NameValueCollection data
)
Summary
Uploads the specified name/value collection to the specified resource with the specified URI using the specified method.
C# Syntax:
public byte[] UploadValues(
   string address,
   string method,
   NameValueCollection data
);
Parameters:

address

The URI of the resource to receive the collection.

method

The method verb used to send the file to the resource.

data

The NameValueCollection to send to the resource.

Return Value:
An array of bytes containing the body of any response from the resource.
Exceptions
Exception Type Condition
WebException An error occurs while opening the stream.

-or-

The Content-type header is not "application/x-www-form-urlencoded".

UriFormatException The URI formed by combining WebClient.BaseAddress, address, and WebClient.QueryString is invalid.
Remarks
The WebClient.UploadValues method sends a NameValueCollection to a resource using the method verb specified in the method parameter and returns any response from the server.

The WebClient.UploadValues method always sets the Content-type header to "Content-type: application/x-www-form-urlencoded".

If the method parameter specifies a verb that is not understood by the server, the underlying protocol classes determine what occurs. Typically, a WebException is thrown with the WebException.Status property set to indicate the error.

If the WebClient.BaseAddress property is not empty, address must be a relative URI that is combined with WebClient.BaseAddress to form the absolute URI of the requested data. If the WebClient.QueryString property is not empty, it is appended to address.

Example
The following example gathers information from the user (name, age, and address) and posts the values to the server using WebClient.UploadValues. Any response from the server is displayed on the console.
			Console.Write("\nPlease enter the URL to post data to : ");
			string uriString = Console.ReadLine();

			// Create a new WebClient instance.
			WebClient myWebClient = new WebClient();

			// Create a new NameValueCollection instance to hold some custom parameters to be posted to the URL.
			NameValueCollection myNameValueCollection = new NameValueCollection();
			
			Console.WriteLine("Please enter the following parameters to be posted to the URI");
			Console.Write("Name:");
			string name = Console.ReadLine();

			Console.Write("Age:");
			string age = Console.ReadLine();

			Console.Write("Address:");
			string address = Console.ReadLine();

			// Add necessary parameter/value pairs to the name/value container.
			myNameValueCollection.Add("Name",name);			
			myNameValueCollection.Add("Address",address);
			myNameValueCollection.Add("Age",age);
			Console.WriteLine("\nUploading to {0} ...",  uriString);

			// Upload the NameValueCollection.
			byte[] responseArray = myWebClient.UploadValues(uriString,"POST",myNameValueCollection);
			
			// Decode and display the response.
			Console.WriteLine("\nResponse received was :\n{0}",Encoding.ASCII.GetString(responseArray));

    

Return to top


Event: Disposed
Inherited
See base class member description: System.ComponentModel.Component.Disposed

Summary
Adds an event handler to listen to the Component.Disposed event on the component.
C# Syntax:
public event EventHandler Disposed;
Remarks
When you create a Component.Disposed delegate, you identify the method that handles the event. To associate the event with your event handler, add an instance of the delegate to the event. The event handler is called whenever the event occurs, unless you remove the delegate. For more information about the event handler delegates, see the conceptual topic at MSDN: eventsdelegates.
See also:
EventHandler

Return to top


Top of page

Copyright (c) 2002 Microsoft Corporation. All rights reserved.