35

I have this URL: URL from 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?

NoName
  • 7,940
  • 13
  • 56
  • 108
  • do you want to do this via C# code? – shenku Sep 03 '12 at 00:46
  • possible duplicate of [How to download a file from a URL in C#?](http://stackoverflow.com/questions/307688/how-to-download-a-file-from-a-url-in-c) or [Download file from URL to a string](http://stackoverflow.com/questions/3231969/download-file-from-url-to-a-string). – adrianbanks Sep 03 '12 at 00:47
  • download, read, and delete the file. – Pedro Lobito Sep 03 '12 at 00:49

4 Answers4

57
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.

Or as adrianbanks mentioned below simply use WebClient.DownloadString()

Community
  • 1
  • 1
Josh
  • 44,706
  • 7
  • 102
  • 124
  • 15
    What's wrong with using [`WebClient.DownloadString()`](http://msdn.microsoft.com/en-us/library/system.net.webclient.downloadstring.aspx), which can do the same in a single line of code? – adrianbanks Sep 03 '12 at 00:55
  • Nothing... I guess I am just so used to using WebRequest because I am hardly ever just getting a single resource, or have to deal with headers. To be honest it didn't even pop into my head until you mentioned it just now. – Josh Sep 03 '12 at 00:57
  • @adrianbanks - for one, I don't believe it works in a PCL. – jbyrd Mar 01 '18 at 19:55
53

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

Edit, 2022 Update (using System.Net.Http;):

var result = await new HttpClient().GetStringAsync("https://example.com/test.txt");
Kyle
  • 32,731
  • 39
  • 134
  • 184
  • 1
    Don't like the idea of not cleaning up the `WebClient` object. Always like to use those in using blocks. – Wobbles Jul 28 '16 at 14:29
13

Since this question and my previous answer is fairly old now, a more modern answer would be to use HttpClient from 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");
        }
    }
}

If not within an async function, then:

string result = client.GetStringAsync("https://example.com/test.txt").Result;
Kyle
  • 32,731
  • 39
  • 134
  • 184
3

For asp.net core / .Net 5+, you should inject HttpClient in your service. You should not manually create a new instance.

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

Injecting HttpClient will use IHttpClientFactory behind the scenes. Docs: https://learn.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests

Christoph Lütjen
  • 5,403
  • 2
  • 24
  • 33