The locale en-EN is an invalid culture identifier

耗尽温柔 提交于 2021-02-20 18:58:38

问题


I recently shifted from a computer which had Windows 10 with VS 2017 to a computer which had Windows 8.1 with VS 2017. I was working with a piece of code which had a line like this. Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(locale);

Here, locale value is en-EN. I got hit with a surprise when this threw a CultureNotFoundException exception with a message.

en-EN is an invalid culture identifier.

Surprising to me because, the same code with locale as en-EN works in Windows 10.

I have checked for a few solutions. Does Windows 8.1 not support a few locales? Can the missing locales be added? Or, is this a problem that is completely unrelated to the OS. Any help is appreciated!


回答1:


Yes, en-EN is really an invalid culture identifier. However, in Windows 10 the behavior of handling invalid identifiers changed a bit.

You have basically two options:

  1. Use a valid identifier. For English in England you should use en-GB
  2. If your desired England culture differs from en-GB, then register a new culture.

This is how you can register a new culture:

Cultures have a hierarchy where the root is always the CultureInfo.InvariantCulture. Conventionally, culture names reflect this hierarchy. So for example, en-GB, which is a region-specific (Great Britain) culture, is derived from en, which is the region-independent English culture, and its parent is the invariant culture.

If you want to create an England-specific culture derived from en-GB, then you should call it something like en-GB-England

var parent = CultureInfo.GetCultureInfo("en-GB");
var builder = new CultureAndRegionInfoBuilder("en-GB-England", CultureAndRegionModifiers.None);
builder.LoadDataFromCultureInfo(parent);
builder.LoadDataFromRegionInfo(new RegionInfo(parent.Name));
builder.Parent = parent;
builder.CultureEnglishName = "English (Great Britain, England)";
builder.CultureNativeName = builder.CultureEnglishName;

try
{
    builder.Register();
}
catch (UnauthorizedAccessException e)
{
    // You must run this code with Administrator rights
     throw;
}
catch (InvalidOperationException e) when (e.Message.Contains("already exists"))
{
    // culture is already registered
}

var enEN = CultureInfo.GetCultureInfo("en-GB-England");


来源:https://stackoverflow.com/questions/50810120/the-locale-en-en-is-an-invalid-culture-identifier

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!