Downloading Data from a Server
Problem
You need to download data from a location specified by a URL; this data can be either an array of bytes or a file.
Solution
Use the WebClient.DownloadData method to download data from a URL:
string uri = "http://localhost/mysite/index.aspx";
// Make a client
using (WebClient client = new WebClient())
{
// Get the contents of the file
Console.WriteLine("Downloading {0} " + uri);
// Download the page and store the bytes
byte[] bytes;
try
{
bytes = client.DownloadData(uri);
}
catch (WebException we)
{
Console.WriteLine(we.ToString());
return;
}
// Write the content out
string page = Encoding.ASCII.GetString(bytes);
Console.WriteLine(page);
}
This will produce the following output:
Downloading {0} http://localhost/mysite/index.aspx
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>WebForm1</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema"
content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body MS_POSITIONING="GridLayout">
<form name="Form1" method="post" action="index.aspx" id="Form1">
<input type="hidden" name="__VIEWSTATE"
value="dDwyMDQwNjUzNDY2Ozs+kS9hguYm9369sybDqmIow0AvxBg=" />
<span id="Label1" style="Z-INDEX: 101; LEFT: 142px; POSITION: absolute;
TOP: 164px">This is index.aspx!</span>
</form>
</body>
</HTML>
You can also download data to a file using DownloadFile:
// Make a client
using (WebClient client = new WebClient())
{
// Go get the file
Console.WriteLine("Retrieving file from {0}…\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);
}
This will produce the following output:
Retrieving file from http://localhost/mysite/index.aspx…
Downloaded http://localhost/mysite/index.aspx to C:\Documents and Settings\[user]\
Local Settings\Temp\tmp17C.tmp
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.
|