The WebClient Class


If you only want to request a file from a particular URI, you will find that the easiest .NET class to use is System.Net.WebClient. This is an extremely high-level class designed to perform basic operations with only one or two commands. The .NET Framework currently supports URIs beginning with the http:, https:, and file: identifiers.

Tip 

It is worth noting that the term URL (Uniform Resource Locator) is no longer in use in new technical specifications, and URI (Uniform Resource Identifier) is now preferred. URI has roughly the same meaning as URL, but is a bit more general because URI does not imply you are using one of the familiar protocols, such as HTTP or FTP.

Downloading Files

Two methods are available for downloading a file using WebClient. The method you choose depends on how you want to process the file’s contents. If you simply want to save the file to disk, you use the DownloadFile() method. This method takes two parameters: the URI of the file and a location (path and file name) to save the requested data:

  WebClient Client = new WebClient(); Client.DownloadFile("http://www.reuters.com/", "ReutersHomepage.htm"); 

More commonly, your application will want to process the data retrieved from the Web site. To do this, you use the OpenRead() method. OpenRead() returns a Stream reference you can then use to retrieve the data into memory:

  WebClient Client = new WebClient(); Stream strm = Client.OpenRead("http://www.reuters.com/"); 

Basic Web Client Example

The first example demonstrates the WebClient.OpenRead() method. You will display the contents of the downloaded page in a ListBox control. To begin, create a new project as a standard C# Windows Forms application and add a ListBox called listBox1 with the docking property set to DockStyle.Fill. At the beginning of the file, you will need to add the System.Net and System.IO namespaces references to your list of using directives. You then make the following changes to the constructor of the main form:

 public Form1() {    InitializeComponent();        WebClient Client = new WebClient();    Stream strm = Client.OpenRead("http://www.reuters.com");    StreamReader sr = new StreamReader(strm);    string line;    while ( (line=sr.ReadLine()) != null )    {       listBox1.Items.Add(line);    }    strm.Close(); }

In this example, you connect a StreamReader class from the System.IO namespace to the network stream. This allows you to obtain data from the stream as text through the use of higher-level methods, such as ReadLine(). This is an excellent example of the point made in Chapter 24, “Manipulating Files and the Registry,” about the benefits of abstracting data movement into the concept of a stream.

Figure 35-1 shows the results of running this sample code.

image from book
Figure 35-1

The WebClient class also has an OpenWrite() method. This method returns a writable stream for you to send data to a URI. You can also specify the method used to send the data to the host; the default method is POST. The following code snippet assumes a writable directory named accept on the local machine. The code will create a file in the directory with the name newfile.txt and the contents Hello World:

  WebClient webClient = new WebClient(); Stream stream = webClient.OpenWrite("http://localhost/accept/newfile.txt", "PUT"); StreamWriter streamWriter = new StreamWriter(stream); streamWriter.WriteLine("Hello World"); streamWriter.Close(); 

Uploading Files

The WebClient class also features UploadFile() and UploadData() methods. UploadFile() uploads a file to a specified location given the local file name, whereas UploadData() uploads binary data supplied as an array of bytes to the specified URI (there is also a DownloadData() method for retrieving an array of bytes from a URI):

  WebClient client = new WebClient(); client.UploadFile("http://www.ourwebsite.com/NewFile.htm",                   "C:\\WebSiteFiles\\NewFile.htm"); byte[] image; // code to initialize image so it contains all the binary data for // some jpg file client.UploadData("http://www.ourwebsite.com/NewFile.jpg", image); 




Professional C# 2005 with .NET 3.0
Professional C# 2005 with .NET 3.0
ISBN: 470124725
EAN: N/A
Year: 2007
Pages: 427

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net