How to get ISO 3166 Country Code from CultureInfo in .NET

1.1k Views Asked by At

Given a CultureInfo object, how do I get the two character ISO 3166 Country Code? E.g. from en-US, I want US and from en-GB, I want GB. I also need to handle cases where the culture may not have a country code.

2

There are 2 best solutions below

0
Esko On

Use RegionInfo-class to retrieve two (or three) letter iso region name:

RegionInfo usa = new RegionInfo("en-US");           
string isoUSA = usa.TwoLetterISORegionName;

RegionInfo gb = new RegionInfo("en-GB");
string isoGB = gb.TwoLetterISORegionName;

You might want to catch possible exception that will happen if you try to pass invalid value to the constructor.

0
Sasha Ibraimov On

You can use this package

This library that provides access to ISO standards, including ISO 639 (language codes), ISO 3166 (country codes), and ISO 4217 (currency codes).

Example:

Country[] countries = Countries.Collection.Where(c => c.Name[0] == 'A').ToArray();
foreach (Country country in countries)
{
   Language[] langs = country.GetLanguages();
   Currency[] currencies = country.GetCurrencies();
   string langsColumn = string.Join(',', langs.Select(l => l.Name));
   string currenciesColumn = string.Join(',', currencies.Select(l=>l.Alpha3));
   Console.WriteLine($"{country.Alpha2};{country.Name};{currenciesColumn};{langsColumn}");
}