2009-02-28 14 views

cevap

47

System.Net.WebClient sınıfını kullanın.

System.Console.WriteLine(new System.Net.WebClient().DownloadString(url)); 
+2

Nice !! :-) +1 benden! Noktasına doğru! –

+2

Ancak, senkron olurdu. Anlamı, yalnızca tüm sayfa yüklendikten sonra verileri gösterecektir. – configurator

+3

Sexy one liner ... satıldı! +1 –

19

Ben bir örnek hamile adres: Burada

WebRequest r = WebRequest.Create("http://www.msn.com"); 
WebResponse resp = r.GetResponse(); 
using (StreamReader sr = new StreamReader(resp.GetResponseStream())) 
{ 
    Console.WriteLine(sr.ReadToEnd()); 
} 

Console.ReadKey(); 

bu kez WebClient'ı kullanarak, başka bir seçenektir ve uyumsuz bunu:

static void Main(string[] args) 
{ 
    System.Net.WebClient c = new WebClient(); 
    c.DownloadDataCompleted += 
     new DownloadDataCompletedEventHandler(c_DownloadDataCompleted); 
    c.DownloadDataAsync(new Uri("http://www.msn.com")); 

    Console.ReadKey(); 
} 

static void c_DownloadDataCompleted(object sender, 
            DownloadDataCompletedEventArgs e) 
{ 
    Console.WriteLine(Encoding.ASCII.GetString(e.Result)); 
} 

İkinci seçenek bunun gibi kullanışlı olduğunu UI Thread'i daha iyi bir deneyim vererek engellemez.

+0

UI iş parçacığı mı? Bu bir konsol uygulaması değil mi? –

+1

Örneğimin bir konsol uygulamasıyla kullanmanın tek amacı olduğunu belirtmedim. –

+0

Katılıyorum ama bahsettiğiniz kesin örnekte özellikle bir şey gösterdiğimi düşünüyorum * yanlış * (yalnızca konsol sürümünde): URL getirilmeden önce bir tuşa basılması, konsolun herhangi bir şey yazılmadan önce kapatılmasına neden olur. 'Main' yönteminin adını değiştirmek niyetinizi daha iyi gösterir. –

5
// Save HTML code to a local file. 
WebClient client = new WebClient(); 
client.DownloadFile("http://yoursite.com/page.html", @"C:\htmlFile.html"); 

// Without saving it. 
string htmlCode = client.DownloadString("http://yoursite.com/page.html"); 
İlgili konular