网络编程(一):用C#下载网络文件的2种方法

时间:2021-02-27 17:19:31

使用C#下载一个Internet上的文件主要是依靠HttpWebRequest/HttpWebResonse和WebClient。具体处理起来还有同步和异步两种方式,所以我们其实有四种组合。

1、使用HttpWebRequest/HttpWebResonse和WebClient

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); 
WebResponse response = request.GetResponse(); 
Stream stream = response.GetResponseStream();

if (!response.ContentType.ToLower().StartsWith("text/")) 

    //Value = SaveBinaryFile(response, FileName); 
    byte[] buffer = new byte[1024]; 
    Stream outStream = System.IO.File.Create(FileName); 
    Stream inStream = response.GetResponseStream();

int l; 
    do 
    { 
        l = inStream.Read(buffer, 0, buffer.Length); 
        if (l > 0) 
            outStream.Write(buffer, 0, l); 
    } 
    while (l > 0);

outStream.Close(); 
    inStream.Close(); 
}

2、使用WebClient

string url = "http://www.mozilla.org/images/feature-back-cnet.png"; 
WebClient myWebClient = new WebClient(); 
myWebClient.DownloadFile(url,"C:\\temp\\feature-back-cnet.png");

3、异步调用

异步调用可参见:http://wenku.baidu.com/view/f47cc781e53a580216fcfe64.html