Monday, February 21, 2022

c# - How to download file from the web as string

Useful for example for .xml downloading. 

Old (now obsolete method):
string str = "";
#pragma warning disable SYSLIB0014 // Type or member is obsolete
using( var wc = new WebClient() )
{
  str = wc.DownloadString( this.URL );
}
#pragma warning restore SYSLIB0014 // Type or member is obsolete
New method:
string str = "";
HttpClient client = new HttpClient();
using ( HttpResponseMessage response = client.GetAsync( this.URL ).Result )
{
  using ( HttpContent content = response.Content )
  {
    str = content.ReadAsStringAsync().Result;
  }
}

No comments:

Post a Comment