Risposte:
Puoi scaricare file con la classe WebClient :
using System.Net;
using (WebClient client = new WebClient ()) // WebClient class inherits IDisposable
{
client.DownloadFile("http://yoursite.com/page.html", @"C:\localfile.html");
// Or you can get the file content without saving it
string htmlCode = client.DownloadString("http://yoursite.com/page.html");
}
fondamentalmente:
using System.Net;
using System.Net.Http; // in LINQPad, also add a reference to System.Net.Http.dll
WebRequest req = HttpWebRequest.Create("http://google.com");
req.Method = "GET";
string source;
using (StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream()))
{
source = reader.ReadToEnd();
}
Console.WriteLine(source);
La risposta più recente, più recente, aggiornata
Questo post è molto vecchio (ha 7 anni quando ho risposto), quindi nessuna delle altre risposte ha utilizzato il modo nuovo e consigliato, che è la HttpClientclasse.
HttpClientè considerata la nuova API e dovrebbe sostituire quelle vecchie ( WebCliente WebRequest)
string url = "page url";
HttpClient client = new HttpClient();
using (HttpResponseMessage response = client.GetAsync(url).Result)
{
using (HttpContent content = response.Content)
{
string result = content.ReadAsStringAsync().Result;
}
}
per maggiori informazioni su come usare la HttpClientclasse (specialmente nei casi asincroni), puoi fare riferimento a questa domanda
NOTA 1: se si desidera utilizzare async / await
string url = "page url";
HttpClient client = new HttpClient();
using (HttpResponseMessage response = await client.GetAsync(url))
{
using (HttpContent content = response.Content)
{
string result = await content.ReadAsStringAsync();
}
}
NOTA 2: se si utilizzano le funzionalità C # 8
string url = "page url";
HttpClient client = new HttpClient();
using HttpResponseMessage response = await client.GetAsync(url);
using HttpContent content = response.Content;
string result = await content.ReadAsStringAsync();
Puoi ottenerlo con:
var html = new System.Net.WebClient().DownloadString(siteUrl)
Disposeil WebClient?
Il modo @cms è il più recente, suggerito nel sito di MS, ma ho avuto un problema difficile da risolvere, con entrambi i metodi pubblicati qui, ora posto la soluzione per tutti!
problema:
se usi un URL come questo: www.somesite.it/?p=1500in alcuni casi ottieni un errore interno del server (500), anche se nel browser web www.somesite.it/?p=1500funziona perfettamente.
soluzione: devi spostare i parametri, il codice di lavoro è:
using System.Net;
//...
using (WebClient client = new WebClient ())
{
client.QueryString.Add("p", "1500"); //add parameters
string htmlCode = client.DownloadString("www.somesite.it");
//...
}