问题
I have a string which I need to verify if it's a Country code. The culture is German. Is there any method that I can call to get a list of Country codes in a German culture without having to type out all the 274 (?) codes myself?
Thanks, Teja.
回答1:
When you say "country code" I assume you mean the two-letter code as in ISO 3166. Then you can use the RegionInfo constructor to check if your string is a correct code.
string countryCode = "de";
try {
RegionInfo info = new RegionInfo(countryCode);
}
catch (ArgumentException argEx)
{
// The code was not a valid country code
}
You could also, as you state in your question, check if it is a valid country code for the german language. Then you just pass in a specific culture name together with the country code.
string language = "de";
string countryCode = "de";
try {
RegionInfo info = new RegionInfo(string.Format("{0}-{1}", language, countryCode));
}
catch (ArgumentException argEx)
{
// The code was not a valid country code for the specified language
}
回答2:
The accepted answer is a misuse of the ArgumentException
thrown by the constructor. You're not really using the RegionInfo
or the ArgumentException
instances, which makes the code's purpose very unclear.
Instead, get a list of all specific cultures, then search through the regions of those cultures to find a match on your ISO 3166 alpha-2 code:
bool IsCountryCodeValid(string countryCode)
{
return CultureInfo
.GetCultures(CultureTypes.SpecificCultures)
.Select(culture => new RegionInfo(culture.LCID))
.Any(region => region.TwoLetterISORegionName == countryCode);
}
Or specifically, for your problem:
bool IsValidGermanCountryCode(string countryCode)
{
return CultureInfo
.GetCultures(CultureTypes.SpecificCultures)
.Where(culture => culture.TwoLetterISOLanguageName == "de")
.Select(culture => new RegionInfo(culture.LCID))
.Any(region => region.TwoLetterISORegionName == countryCode);
}
回答3:
If you only need countries/regions, you can make use of the RegionInfo class: http://msdn.microsoft.com/en-us/library/system.globalization.regioninfo.aspx
回答4:
Be careful when using RegionInfo
to check for a valid ISO code. It will return a region if the code you supply is valid AND it is a supported region, but it will not do this for all valid ISO 3166 codes.
See here for a fuller explanation: https://social.msdn.microsoft.com/Forums/en-US/c9a8bc14-d571-4702-91a6-1b80da239009/question-of-regioninfo-and-region-cy
RegionInfo
will work fine for Europe, but there are several African countries that aren't validated with this method (e.g. Uganda).
回答5:
http://cldr.unicode.org/ - common standard multilanguage database include country list and other localizable data.
来源:https://stackoverflow.com/questions/1324048/country-codes-list-c-sharp