How could I use C# to download the 开发者_运维问答contents of a URL, and store the text in a string, without having to save the file to the hard drive?
string contents;
using (var wc = new System.Net.WebClient())
contents = wc.DownloadString(url);
Use a WebClient
var result = string.Empty;
using (var webClient = new System.Net.WebClient())
{
result = webClient.DownloadString("http://some.url");
}
See WebClient.DownloadString. Note there is also a WebClient.DownloadStringAsync method, if you need to do this without blocking the calling thread.
use this Code Simply
var r= string.Empty;
using (var web = new System.Net.WebClient())
r= web.DownloadString("http://TEST.COM");
using System.IO;
using System.Net;
WebClient client = new WebClient();
string dnlad = client.DownloadString("http://www.stackoverflow.com/");
File.WriteAllText(@"c:\Users\Admin\Desktop\Data1.txt", dnlad);
got it from MVA hope it helps
None Obsolete solution:
async:
var client = new HttpClient();
using HttpResponseMessage response = client.GetAsync(url).Result;
using HttpContent content = response.Content;
var r = await content.ReadAsStringAsync();
sync:
var client = new HttpClient();
using HttpResponseMessage response = client.GetAsync(url).Result;
using HttpContent content = response.Content;
var r = content.ReadAsStringAsync().Result;
For more simpler and none-obsolete solution:
using var client = new HttpClient();
var content = client.GetStringAsync(url).result
精彩评论