Recipe 13.12 Downloading Data from a Server

Problem

You need to download data from a location specified by a URI; this data can be either an array of bytes or a file.

Solution

Use the WebClient DownloadData and DownloadFile methods to download the bytes of a file from a URI:

 string uri = "http://localhost/mysite/upload.aspx"; // make a client WebClient client = new WebClient( ); // get the contents of the file Console.WriteLine("Downloading {0} " + uri); // download the page and store the bytes byte[] bytes = client.DownloadData (uri); // Write the HTML out string page = Encoding.ASCII.GetString(bytes); Console.WriteLine(page); 

You could also have downloaded the file itself:

 // go get the file Console.WriteLine("Retrieving file from {1}...\r\n", uri); // get file and put it in a temp file string tempFile = Path.GetTempFileName( ); client.DownloadFile(uri,tempFile);         Console.WriteLine("Downloaded {0} to {1}",uri,tempFile); 

Discussion

WebClient simplifies downloading of files and bytes in files, as these are common tasks when dealing with the Web. The more traditional stream-based method for downloading can also be accessed via the OpenRead method on the WebClient .

See Also

See the "WebClient Class" topic in the MSDN documentation.



C# Cookbook
C# 3.0 Cookbook
ISBN: 059651610X
EAN: 2147483647
Year: 2003
Pages: 315

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