11.1 Download a File over HTTP


Problem

You need a quick, simple way to download a file from a Web site over HTTP.

Solution

Use the static DownloadFile method of System.Net.WebClient class.

Discussion

The .NET Framework provides several mechanisms for sending data over HTTP. One of the easiest approaches is to use the System.Net.WebClient helper class. It provides higher-level methods like DownloadFile and UploadFile . These methods don't have any built-in support for asynchronous communications or authentication. If you need these features, you can use the more sophisticated functionality provided in the WebRequest and WebResponse classes, as described in recipes 11.2 and 11.3.

The following application downloads a graphic named banner.gif from a Microsoft Web site and stores it locally.

 using System; using System.Net; using System.IO; public class Download {     private static void Main() {         string remoteUri =           "http://www.microsoft.com/mspress/images/banner.gif";         string localFileName = "banner.gif";         WebClient client = new WebClient();         Console.WriteLine("Downloading file " +          remoteUri + " to " + Path.GetFullPath(localFileName));         // Perform the download.         client.DownloadFile(remoteUri, localFileName);                 Console.WriteLine("Download complete.");         Console.ReadLine();     } } 



C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

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