I've got a list of ISO 3166 two-letter country codes acquired from an external source. For each, I create
new System.Globalization.RegionInfo(countryCode)
and occasionally one is invalid resulting in an ArgumentException "Culture name 'xx' is not supported."
I want a function to determine if the country code is valid before I pass it into the constructor. This is my attempt:
private bool IsCultureValid(string cultureName)
{
return CultureInfo.GetCultures(CultureTypes.AllCultures)
.Any(c => c.Name.Equals(cultureName, StringComparison.InvariantCultureIgnoreCase));
}
The function returns a false negative for many inputs (function returns false, but I can create a RegionInfo object with that input if I try). Some inputs:
- zw (Zimbabwe)
- au (Australia)
- mx (Mexico)
- ve (Bolivarian Republic of Venezuela)
- hn (Honduras)
- kw (Kuwait)
What am I missing? Is there a better approach here? Thanks in advance!
I realize this is a dated question. However, I recently ran across a similar situation where I needed to validate incoming ISO currency codes. All of the examples I could find here and elsewhere relied on catching the exception that was thrown when attempting to create a region or culture with an invalid code/id. Which is just not a good practice.
My own research into the problem led me to realize that for the most part, the problem was the invariant culture and neutral cultures. Once they are removed from the CultureInfo array it is possible to generate a list of only valid RegionInfo objects.
This is an extrapolation from my own issue to provide the requested answer. Though obviously a variation of this could be applied anywhere you need just the valid RegionInfo objects.
Edit: Unless using custom cultures this can actually be done even more directly. Simply use the "CultureTypes.SpecificCultures" enum value.