Get list of possible country codes from BCP-47 code using System.Globalization

604 Views Asked by At

I'm trying to guess which country a BCP-47 code belongs to. I'm aware that this would provide a list of multiple countries. Nevertheless, I would like to try.

Is that possible using any of the classes within System.Globalization?

Why I'm doing this: On my website, I would like to auto fill a country. I'm first attempting to geolocate the IP address. If that fails, I would like to try and guess the country using navigator.language (JavaScript).

This fails for e.g. nb (Norwegian Bokmål -- ideally it would produce Norway):

var cultureInfo = new CultureInfo("nb");
var regionInfo = new RegionInfo(cultureInfo.LCID); // Throws because culture is not neutral

Is it perhaps possible to aggregate some data from System.Globalization and create a dictionary of sorts upon initialization?

1

There are 1 best solutions below

2
DubDub On

No, I don't think System.Globalization is going to help you, and you won't be able to do what you want to do easily.

What I'd recommend is pulling this table out of this wikipedia article: https://en.wikipedia.org/wiki/List_of_official_languages_by_country_and_territory

Stick it in a csv, load it in and do a foreach over the full set of country codes, map them against your csv based on the information in your CultureInfo() object.

Eventually, you should be able to build up a list of countries to each code you've got. You likely won't be able to get them all, but you'll probably get decent coverage, and a few headaches figuring it out.

I haven't looked, but I wouldn't be surprised if what you want has been put into some nuget package somewhere.