Question

I have a country name like Australia and I would like to get the ISO 3166-1 alpha 2 code like AU in this case. Is there a way to easily do this in .NET?

Was it helpful?

Solution 2

There is nothing built in to convert a country name to its 2 alpha ISO code.

You can create a dictionary to map between the two.

var countryToISO2Map = new Dictionary<string,string>{
   {"Australia", "AU"},
   ...      
};

OTHER TIPS

Similar question asked in Country name to ISO 3166-2 code

    /// <summary>
    /// English Name for country
    /// </summary>
    /// <param name="countryEnglishName"></param>
    /// <returns>
    /// Returns: RegionInfo object for successful find.
    /// Returns: Null if object is not found.
    /// </returns>
    static RegionInfo getRegionInfo (string countryEnglishName)
    {
        //Note: This is computed every time. This may be optimized
        var regionInfos = CultureInfo.GetCultures(CultureTypes.SpecificCultures)
           .Select(c => new RegionInfo(c.LCID))
           .Distinct()
           .ToList();
         RegionInfo r = regionInfos.Find(
                region => region.EnglishName.ToLower().Equals(countryEnglishName.ToLower()));                       
         return r;
    }

You can get a JSON mapping of country codes to names from http://country.io/names.json. You'd just need to flip this with something like:

var countries = codes.ToDictionary(x => x.Value, x => x.Key);

And then you could easily get the country code from the new dictionary.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top