ASP.Net C# DownloadString vs DownloadData Encoding Examples

I recently came across an issue using the WebClient.DownloadString method in System.Net that was causing UTF8 encoded data to not come through properly, and instead was showing odd characters.

Researching the issue led me to the following Stack Overflow articles:

The accepted answers on both work well, so I've put together an example using C# to illustrate the behavior and results.

DownloadString (no encoding specified)
// variables
string Url = "https://mysafeinfo.com/api/data?list=states&format=json&alias=nm=name,ab=code,cp=capital,yr=year&select=capital&ab=GU";
  
// DownloadString (no encoding specified)
using (WebClient client = new WebClient())
{
    Console.WriteLine(client.DownloadString(Url));
}

// result
[
  {
    "capital": "Hagåtña Dededo"
  }
]

DownloadString (encoding specified)
// variables
string Url = "https://mysafeinfo.com/api/data?list=states&format=json&alias=nm=name,ab=code,cp=capital,yr=year&select=capital&ab=GU";
  
// DownloadString (encoding specified)
using (WebClient client = new WebClient())
{
    // specify encoding
    client.Encoding = System.Text.UTF8Encoding.UTF8;
   
    // output
    Console.WriteLine(client.DownloadString(Url));
}

// result
[
  {
    "capital": "Hagåtña Dededo"
  }
]

DownloadData (encoding specified)
// variables
string Url = "https://mysafeinfo.com/api/data?list=states&format=json&alias=nm=name,ab=code,cp=capital,yr=year&select=capital&ab=GU";
  
// DownloadData (encoding specified)
using (WebClient client = new WebClient())
{
    Console.WriteLine(System.Text.UTF8Encoding.UTF8.GetString(client.DownloadData(Url)));
}

// result
[
  {
    "capital": "Hagåtña Dededo"
  }
]

Matt Pavey is a Microsoft Certified software developer who specializes in ASP.Net, VB.Net, C#, AJAX, LINQ, XML, XSL, Web Services, SQL, jQuery, and more. Follow on Twitter @matthewpavey

No comments: