2008-08-25 73 views

回答

56
public static void DownloadFile(string remoteFilename, string localFilename) 
{ 
    WebClient client = new WebClient(); 
    client.DownloadFile(remoteFilename, localFilename); 
} 
+6

這是最慢的!,實例化一個新的WebClient有3-5個延遲,然後它實際上下載我聽說它是​​由於檢查代理支持。我建議使用套接字方式下載,因爲這是最快的解決方案 – SSpoke 2015-09-30 01:15:39

23

System.Net.WebClient

從MSDN:

using System; 
using System.Net; 
using System.IO; 

public class Test 
{ 
    public static void Main (string[] args) 
    { 
     if (args == null || args.Length == 0) 
     { 
      throw new ApplicationException ("Specify the URI of the resource to retrieve."); 
     } 
     WebClient client = new WebClient(); 

     // Add a user agent header in case the 
     // requested URI contains a query. 

     client.Headers.Add ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"); 

     Stream data = client.OpenRead (args[0]); 
     StreamReader reader = new StreamReader (data); 
     string s = reader.ReadToEnd(); 
     Console.WriteLine (s); 
     data.Close(); 
     reader.Close(); 
    } 
} 
+5

願望MSDN實際上在他們的榜樣處置IDisposable的資源的方法。一個小例外和Stream/StreamReader不會被清理。 `使用'是你的朋友。 – 2012-06-05 00:53:44

22

使用來自System.Net WebClient類;在.NET 2.0和更高版本上。

WebClient Client = new WebClient(); 
Client.DownloadFile("http://mysite.com/myfile.txt", " C:\myfile.txt"); 
4

這裏是我的答案,這需要一個URL,並返回一個字符串

public static string downloadWebPage(string theURL) 
    { 
     //### download a web page to a string 
     WebClient client = new WebClient(); 

     client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"); 

     Stream data = client.OpenRead(theURL); 
     StreamReader reader = new StreamReader(data); 
     string s = reader.ReadToEnd(); 
     return s; 
    } 
3

WebClient.DownloadString

public static void DownloadString (string address) 
{ 
    WebClient client = new WebClient(); 
    string reply = client.DownloadString (address); 

    Console.WriteLine (reply); 
}