2008-08-25 11 views

Répondre

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

Ceci est le plus lent !, instanciation d'un nouveau WebClient a 3-5 retard avant qu'il ne fait le téléchargement j'ai entendu dire que c'est dû à la vérification du support proxy. Je recommande d'utiliser une approche Socket pour télécharger car c'est la solution la plus rapide possible – SSpoke

+2

J'ai interprété le plus rapidement comme "avec le moins de lettres de code possible". –

23

System.Net.WebClient

De 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

souhaits MSDN serait en fait disposer des ressources IDisposable dans leurs exemples. Une petite exception et Stream/StreamReader ne seront pas nettoyés. 'utiliser 'est votre ami. –

22

Utilisez la classe WebClient de System.Net; sur .NET 2.0 et supérieur.

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

voici ma réponse, une méthode qui prend une URL et retourne une chaîne

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