Yanıtlar:
Dosyaları WebClient sınıfıyla indirebilirsiniz :
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");
}
temelde:
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);
En yeni, en yeni, güncel cevap
Bu gönderi gerçekten eski (cevapladığımda 7 yaşında), bu yüzden diğer cevaplardan hiçbiri yeni ve önerilen yolu, yani HttpClientsınıf olanı kullanmadı .
HttpClientyeni API olarak kabul edilir ve eskilerinin yerini almalıdır ( WebClientve 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;
}
}
HttpClientSınıfın nasıl kullanılacağı hakkında daha fazla bilgi için (özellikle eşzamansız durumlarda), bu soruya başvurabilirsiniz.
NOT 1: Async / await kullanmak istiyorsanız
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();
}
}
NOT 2: C # 8 özelliklerini kullanıyorsanız
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();
Şununla elde edebilirsiniz:
var html = new System.Net.WebClient().DownloadString(siteUrl)
DisposeWebClient
@cms yöntemi MS web sitesinde önerilen daha yeni yöntemdir, ancak çözmem gereken zor bir sorun vardı, her iki yöntem de burada yayınlandı, şimdi herkes için çözümü gönderiyorum!
sorun:
bunun gibi bir url kullanırsanız: www.somesite.it/?p=1500bazı durumlarda dahili bir sunucu hatası (500) alırsınız, ancak web tarayıcısında bu www.somesite.it/?p=1500mükemmel çalışır.
çözüm: parametreleri taşımalısınız, çalışma kodu:
using System.Net;
//...
using (WebClient client = new WebClient ())
{
client.QueryString.Add("p", "1500"); //add parameters
string htmlCode = client.DownloadString("www.somesite.it");
//...
}