我有这个网址:URL from Google
当在新标签页中打开链接时,浏览器会强制我下载它。下载后,我得到一个名为“s”的文本文件。但我希望使用C#访问此URL并获取其文本,不要将其作为文件保存到计算机。有办法做到这一点吗?
答案 0 :(得分:43)
var webRequest = WebRequest.Create(@"http://yourUrl");
using (var response = webRequest.GetResponse())
using(var content = response.GetResponseStream())
using(var reader = new StreamReader(content)){
var strContent = reader.ReadToEnd();
}
这会将请求的内容放入strContent。
或者,正如下面提到的adrianbanks,只需使用WebClient.DownloadString()
即可答案 1 :(得分:33)
试试这个:
var url = "https://www.google.com.vn/s?hl=vi&gs_nf=1&tok=i-GIkt7KnVMbpwUBAkCCdA&cp=5&gs_id=n&xhr=t&q=thanh&pf=p&safe=off&output=search&sclient=psy-ab&oq=&gs_l=&pbx=1&bav=on.2,or.r_gc.r_pw.r_cp.r_qf.&fp=be3c25b6da637b79&biw=1366&bih=362&tch=1&ech=5&psi=8_pDUNWHFsbYrQeF5IDIDg.1346632409892.1";
var textFromFile = (new WebClient()).DownloadString(url);
答案 2 :(得分:1)
由于这个问题和我以前的回答已经很老了,一个更现代的答案是使用HttpClient
中的System.Net.Http
using System.Net.Http;
namespace ConsoleApp2
{
class Program
{
async static void Main(string[] args)
{
HttpClient client = new HttpClient();
string result = await client.GetStringAsync("https://example.com/test.txt");
}
}
}
如果不在异步函数中,则:
string result = client.GetStringAsync("https://example.com/test.txt").Result;
答案 3 :(得分:1)
对于asp.net core / .Net 5+,您应该在服务中注入HttpClient。您不应该手动创建新实例。
public class MySerivice {
private readonly HttpClient _httpClient;
public MyService(HttpClient httpClient) {
_httpClient = httpClient;
}
public async Task Foo() {
var myString = await _httpClient.GetStringAsync("https://my-url/file.txt");
}
}
注入HttpClient将在后台使用IHttpClientFactory。文件:https://docs.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests