Odpowiedzi:
Możesz pobierać pliki z klasą 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");
}
gruntownie:
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);
Najnowsza, najnowsza, aktualna odpowiedź
Ten post jest naprawdę stary (ma 7 lat, kiedy na niego odpowiedziałem), więc żadna z pozostałych odpowiedzi nie skorzystała z nowego i zalecanego sposobu, jakim jest HttpClientklasa.
HttpClientjest uważany za nowy interfejs API i powinien zastąpić stare ( WebClienti 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;
}
}
aby uzyskać więcej informacji na temat korzystania z HttpClientklasy (szczególnie w przypadkach asynchronicznych), możesz skierować to pytanie
UWAGA 1: Jeśli chcesz używać 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();
}
}
UWAGA 2: Jeśli używasz funkcji języka 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();
Możesz to zdobyć za pomocą:
var html = new System.Net.WebClient().DownloadString(siteUrl)
Disposejest WebClient?
@cms jest nowszą, sugerowaną na stronie MS, ale miałem trudny problem do rozwiązania, z obiema metodami zamieszczonymi tutaj, teraz zamieszczam rozwiązanie dla wszystkich!
problem:
jeśli używasz takiego adresu URL: www.somesite.it/?p=1500w niektórych przypadkach pojawia się wewnętrzny błąd serwera (500), chociaż w przeglądarce internetowej to www.somesite.it/?p=1500działa doskonale.
rozwiązanie: musisz przenieść parametry, kod roboczy to:
using System.Net;
//...
using (WebClient client = new WebClient ())
{
client.QueryString.Add("p", "1500"); //add parameters
string htmlCode = client.DownloadString("www.somesite.it");
//...
}