C# 如何从此 URL 获取文件中的内容?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12240857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 22:35:21  来源:igfitidea点击:

How to get content from file from this URL?

c#url

提问by Tuyen Pham

I have this URL: URL from Google

我有这个网址:来自 Google 的网址

When open link in new tab, the browser force me download it. After download, I get a text file named "s". But I want use C# access to this URL and get it's text, don't save it as a file to computer. Is any way to do this?

在新选项卡中打开链接时,浏览器会强制我下载它。下载后,我得到一个名为“s”的文本文件。但是我想使用 C# 访问这个 URL 并获取它的文本,不要将它作为文件保存到计算机。有没有办法做到这一点?

采纳答案by Josh

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();
}

This will place the contents of the request into strContent.

这会将请求的内容放入 strContent。

Or as adrianbanksmentioned below simply use WebClient.DownloadString()

或者像下面提到的 adrianbanks简单地使用WebClient.DownloadString()

回答by Kyle

Try this:

尝试这个:

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);

回答by Kyle

Since this question and my previous answer is fairly old now, a more modern answer would be to use HttpClientfrom System.Net.Http

由于这个问题和我以前的答案现在已经很老了,更现代的答案是使用HttpClientfromSystem.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");
        }
    }
}

If not within an async function, then:

如果不在异步函数内,则:

string result = client.GetStringAsync("https://example.com/test.txt").Result;