Question

I will be dealing with a feed that gives me two letter country codes conforming to the ISO 3166-1 alpha-2 standard. So for instance, the United Kingdom has the code GB. My question is, is there some way to easily get back "United Kingdom" when providing "GB" as input into some .NET class or function? In other words is this translation provided by .NET somewhere?

Was it helpful?

Solution

Kind of. .NET uses "cultures", which can be uniquely identified by a combination of language (using ISO 639 two-letter identifiers) and region (using ISO 3166). So, if you know both the language and the region, you can get a descriptive name:

var cultureInfo = new CultureInfo("en-gb");

var cultureName = cultureInfo.EnglishName; //"English (Great Britain)"

//your answer is now the text between the parentheses
var countryName = cultureName.Split('(',')')[1];

Understand that in these cultures, region is secondary to language; there is a culture for every language supported by this system, but not necessarily for every country using that language. That means two things; first, you must know the language (because, for instance, Switzerland and Belgium have two official languages, German and French, and India and the Netherlands each have 4), and second, an ISO code may not exist in the culture list for the language you expect, if the combination of language and region uses symbols and notation close enough to another more well-known culture that it isn't necessary to differentiate (there is, for instance, no "en-CA" culture for English-speaking Canada because it would be identical to "en-US"; there is however a "fr-CA" because Canada's French-language culture is very different from most other French-speaking regions).

The other solution wouldn't be built-in as such, but wouldn't be terribly difficult; find or make yourself a list of the ISO codes and the full country name in either tab-delimited or comma-delimited format, and slurp the file into a Dictionary<string, string> to translate in constant time:

var isoDict = new Dictionary<string, string>();

using(var stream = File.Open("isoCodes.csv"))
{
   using(var reader = new TextReader(stream))
   {
      string currentLine;
      do
      {
        currentLine = reader.ReadLine();
        if(currentLine == null) break;

        //assumes no headers, no format/data errors and 
        //a line format of "cc, Country Name\n";
        //ALWAYS "trust but verify" that the data is sane
        var parts = currentLine.Split(',');
        isoDict.Add(parts[0].Trim(), parts[1].Trim());
      } while(currentLine != null);
   } 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top