[英]Download file from URL to a string
如何使用 C# 下载 URL 的内容,并将文本存储在字符串中,而无需将文件保存到硬盘驱动器?
string contents;
using (var wc = new System.Net.WebClient())
contents = wc.DownloadString(url);
Use a WebClient使用 WebClient
var result = string.Empty;
using (var webClient = new System.Net.WebClient())
{
result = webClient.DownloadString("http://some.url");
}
See WebClient.DownloadString .请参阅WebClient.DownloadString 。 Note there is also a WebClient.DownloadStringAsync method, if you need to do this without blocking the calling thread.
请注意,还有一个WebClient.DownloadStringAsync方法,如果您需要在不阻塞调用线程的情况下执行此操作。
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从MVA得到它希望它有帮助
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.