2008-08-25 24 views

cevap

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

Bu en yavaş !, yeni bir WebClient'in, aslında proxy desteğini kontrol etmek için duyduğunu duyduğum indirme işlemini yapmadan önce 3-5 gecikme olduğunu gösteriyor. Olası en hızlı çözüm olan " – SSpoke

+2

" un en hızlı şekilde "olabildiğince az sayıda kodla" yorumlanması için bir Soket yaklaşımı kullanmanızı tavsiye ederim. –

23

System.Net.WebClient

:

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

İstek MSDN aslında onların örneklerde ıdisposable kaynakların elden verecek bir URL alır ve dönüş bir yöntem. Küçük bir istisna ve Stream/StreamReader temizlenmeyecek. 'using' senin arkadaşın. –

22

Kullanım System.Net gelen WebClient sınıfı; .NET 2.0 ve üstü. Burada

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

cevabım ise, bir dize

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); 
}