CMS*_*CMS 178
您可以使用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");
}
Run Code Online (Sandbox Code Playgroud)
Die*_*cic 39
基本上:
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);
Run Code Online (Sandbox Code Playgroud)
Xen*_*non 17
你可以得到它:
var html = new System.Net.WebClient().DownloadString(siteUrl)
Run Code Online (Sandbox Code Playgroud)
Hak*_*tık 16
这篇文章真的很老了(当我回答它时已经7岁了),所以没有其他解决方案使用新的和推荐的方式,即HttpClient
类.
HttpClient
被认为是新的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;
}
}
Run Code Online (Sandbox Code Playgroud)
有关如何使用HttpClient
该类的更多信息(特别是在异步情况下),您可以参考此问题
Xil*_*iki 11
@cms的方式是最新的,在MS网站上建议,但是我有一个难以解决的问题,这两个方法都贴在这里,现在我发布所有的解决方案!
问题:
如果您使用这样的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");
//...
}
Run Code Online (Sandbox Code Playgroud)