2009-03-01 2 views

답변

155

당신은 WebClient class로 파일을 다운로드 할 수 있습니다 : 기본적으로

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"); 
    //... 
} 
+0

참고 사항 : 더 많은 제어가 필요한 경우 HttpWebRequest 클래스를 살펴보십시오 (예 : 인증을 지정할 수 있음). – Richard

+1

예, HttpWebRequest는 client.UploadData (uriString, "POST", postParamsByteArray)를 사용하여 WebClient를 사용하여 POST 요청을 할 수 있지만 더 많은 제어권을 제공합니다. – CMS

+1

이것 주위에 WebException을 잡는 것이 현명하지 않습니까? 어쩌면 그랬 겠지. 다른 예외 또는 오류를이 메서드로 catch해야합니까? –

33

:

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); 
10

"CMS"방법은 더 최근, MS 웹 사이트

에서 제안하지만 문제가 있었다 해결하기 어렵다, 너비 양쪽 방법 게시

지금 나는 solu 모두를위한

문제 : 당신이이 같은 URL을 사용하는 경우 : 일부 경우에 "www.somesite.it/?p=1500을"당신은 웹 브라우저이 "WWW에 있지만 내부 서버 오류 (500) 를 얻을. somesite.it/?p=1500 "완벽하게 작동합니다.

는 해결 방법 : 매개 변수 (예 쉽습니다) 밖으로 이동해야 , 작업 코드는 다음과 같습니다

using System.Net; 
//... 
using (WebClient client = new WebClient()) 
{ 
    client.QueryString.Add("p", "1500"); //add parameters 
    string htmlCode = client.DownloadString("www.somesite.it"); 
    //... 
} 

여기에 공식 문서 : http://msdn.microsoft.com/en-us/library/system.net.webclient.querystring.aspx

13

당신은 그것을 얻을 수 있습니다 :

var html = new System.Net.WebClient().DownloadString(siteUrl) 
+0

짧고 달콤합니다! Joe Albahari의 예를 읽은 후에 제안을 찾았습니다. LINQPad> 도움말> 새로운 기능 및 캐시 검색. – Colin

+7

var html = new System.Net.WebClient(). DownloadString (siteUrl); // 당신의 클라이언트를 새롭게해야합니다! – user1328350

+4

'WebClient'를'Dispose'합니까? –

4

이 게시물은 정말 오래된 것입니다.), 다른 솔루션 중 아무도 HttpClient 클래스 인 새롭고 권장 된 방법을 사용하지 않았습니다.

HttpClient 새로운 API로 간주되고 있으며 (특히 비동기의 경우)를 HttpClient 클래스를 사용하는 방법에 대한 자세한 내용은, 당신은 참조 할 수 있습니다에 대한 이전 WebClientWebRequest

string url = "page url"; 

using (HttpClient client = new HttpClient()) 
{ 
    using (HttpResponseMessage response = client.GetAsync(url).Result) 
    { 
     using (HttpContent content = response.Content) 
     { 
      string result = content.ReadAsStringAsync().Result; 
     } 
    } 
} 

를 교체해야 this question

관련 문제