50

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?

Chiggins
  • 7,939
  • 21
  • 54
  • 81

6 Answers6

86
string contents;
using (var wc = new System.Net.WebClient())
    contents = wc.DownloadString(url);
mmx
  • 402,675
  • 87
  • 836
  • 780
  • As noted by @CaffGeek you will want to dispose of the `WebClient` in a `using` block. – TrueWill Jul 08 '15 at 13:23
  • This is now Obsolete. When compiling VS gives this warning: `WebRequest, HttpWebRequest, ServicePoint, and WebClient are obsolete. Use HttpClient instead.` It works great though. – Tono Nam May 14 '22 at 22:57
16

Use a WebClient

var result = string.Empty;
using (var webClient = new System.Net.WebClient())
{
    result = webClient.DownloadString("http://some.url");
}
CaffGeek
  • 21,402
  • 17
  • 98
  • 180
5

See WebClient.DownloadString. Note there is also a WebClient.DownloadStringAsync method, if you need to do this without blocking the calling thread.

Danko Durbić
  • 6,887
  • 5
  • 33
  • 38
3

use this Code Simply

var r= string.Empty;
using (var web = new System.Net.WebClient())
       r= web.DownloadString("http://TEST.COM");
alireza amini
  • 1,664
  • 1
  • 17
  • 33
3
using System.IO;
using System.Net;

WebClient client = new WebClient();

string dnlad = client.DownloadString("http://www.stackoverflow.com/");

File.WriteAllText(@"c:\Users\Admin\Desktop\Data1.txt", dnlad);

got it from MVA hope it helps

チーズパン
  • 2,710
  • 8
  • 40
  • 60
GARUDA
  • 31
  • 2
1

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;
Tono Nam
  • 31,694
  • 75
  • 272
  • 444
  • 1
    In your sync example I think you want `GetAwaiter().GetResult()`, it will give you the true exception rather than an aggregate exception. – The Muffin Man May 14 '22 at 23:32