如何从此URL获取文件内容?

Tuy*_*ham 23 c# url

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

在新标签中打开链接时,浏览器强制我下载它.下载后,我得到一个名为"s"的文本文件.但我希望使用C#访问此URL并获取其文本,不要将其作为文件保存到计算机.有办法做到这一点吗?

Jos*_*osh 46

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();
}
Run Code Online (Sandbox Code Playgroud)

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

或者下面提到的adrianbanks只使用WebClient.DownloadString()

  • 使用[`WebClient.DownloadString()`](http://msdn.microsoft.com/en-us/library/system.net.webclient.downloadstring.aspx)有什么问题,它可以在一行中完成相同的操作代码? (14认同)

Kyl*_*yle 35

试试这个:

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);
Run Code Online (Sandbox Code Playgroud)


Kyl*_*yle 8

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

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

string result = client.GetStringAsync("https://example.com/test.txt").Result;
Run Code Online (Sandbox Code Playgroud)