Download file from URL to a string

Viewed 56726

How could I use C# to download the contents of a URL, and store the text in a string, without having to save the file to the hard drive?

7 Answers

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
Related