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.

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.