使用CultureAndRegionInfoBuilder更新内置的.Net文化

时间:2009-07-29 19:03:18

标签: c# .net internationalization

我正在尝试使用以下方法更改内置的.Net文化fr-CA:

    CultureAndRegionInfoBuilder cib = new CultureAndRegionInfoBuilder("fr-CA", CultureAndRegionModifiers.Replacement);

    try
    {
        Console.WriteLine("Updating " + cib.CultureName);

        cib.NumberFormat.CurrencyGroupSeparator = ",";
        cib.NumberFormat.CurrencyDecimalSeparator = ".";
        cib.NumberFormat.NumberGroupSeparator = ",";
        cib.NumberFormat.NumberDecimalSeparator = ".";

        cib.Register();

        Console.WriteLine("Culture updated.");
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
        Console.ReadKey();
    }

但是,Register()调用失败并出现“System.InvalidOperationException:'Register'方法失败,因为自定义文化'fr-CA'已经存在。”

是否可以更新内置文化?根据文档(http://msdn.microsoft.com/en-us/library/system.globalization.cultureandregioninfobuilder.cultureandregioninfobuilder.aspx),看起来我可以更新它,但我可能会读错了。

2 个答案:

答案 0 :(得分:6)

我只需要添加:

CultureAndRegionInfoBuilder.UnRegister("fr-CA");
在注册()之前

答案 1 :(得分:1)

您最好创建现有文化的副本,并使用新名称注册,例如“fr-CACustom”。

[请注意,自定义文化只能由拥有该计算机管理权限的用户在计算机上注册。]

try
{
    CultureAndRegionInfoBuilder cib = new CultureAndRegionInfoBuilder("fr-CACustom", CultureAndRegionModifiers.None);
    cib.LoadDataFromCultureInfo(new CultureInfo("fr-CA"));
    Console.WriteLine("Creating" + cib.CultureName);

    cib.NumberFormat.CurrencyGroupSeparator = ",";
    cib.NumberFormat.CurrencyDecimalSeparator = ".";
    cib.NumberFormat.NumberGroupSeparator = ",";
    cib.NumberFormat.NumberDecimalSeparator = ".";

    // add some region info also
    cib.LoadDataFromRegionInfo(new RegionInfo("CA"));
    cib.RegionEnglishName = "RegionInfo derived from French-speaking Canada";

    cib.Register();

    Console.WriteLine("New culture created.");
}
catch (Exception e)
{
    Console.WriteLine(e);
    Console.ReadKey();
}

此代码在%WINDIR%\ Globalization系统目录中注册由文化名称标识的自定义区域,其中%WINDIR%是Windows操作系统目录。这将使自定义文化可用于其他应用程序。

CultureInfo test = new CultureInfo("fr-CACustom");

[注意:为了能够访问CultureAndRegionInfoBuilder类,您需要对sysglobl程序集的引用,该程序集在大多数Visual Studio项目模板中默认不是引用。]