Country codes list - C#
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
}
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);
}
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