回答:
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");
}
基本的に:
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);
最新、最新、最新の回答
この投稿は本当に古い(私が回答した時点で7歳です)ので、他の回答のどれも、HttpClientクラスである新しい推奨される方法を使用していません。
HttpClient新しいAPIと見なされ、古いAPI(WebClientおよび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;
}
}
HttpClientクラスの使用方法の詳細(特に非同期の場合)については、この質問を参照してください
あなたはそれを得ることができます:
var html = new System.Net.WebClient().DownloadString(siteUrl)
DisposeWebClient
@cms方法はより最近のものであり、MS Webサイトで提案されていますが、解決するのが難しい問題がありました。どちらの方法もここに投稿されているので、今や私はすべての人に解決策を投稿します!
問題:
このようなURLを使用する場合:場合www.somesite.it/?p=1500によっては内部サーバーエラー(500)が発生しますが、Webブラウザーではこれはwww.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");
//...
}