Практическое руководство. Создание настраиваемых региональных параметров

Обновлен: Ноябрь 2007

Языки и региональные параметры, предопределенные в платформе .NET Framework и операционной системе Windows, предоставляют сведения, например, о том, какой язык и календарь используется в стране или регионе, о соглашениях, связанных с текстом, которые используются для форматирования, анализа и сравнения строк, дат и чисел. Однако если предопределенные языки и региональные параметры не обеспечивают необходимых сведений, в приложении можно создать пользовательский язык и региональные параметры.

Определение и создание пользовательского языка и региональных параметров

  1. Для создания и именования пользовательского языка и региональных параметров в приложении нужно использовать объект CultureAndRegionInfoBuilder. Пользовательский язык и региональные параметры могут быть совершенно новыми или заменять существующий язык и региональные параметры платформы .NET Framework или языковой стандарт Windows.

    При создании новых языков и региональных параметров в приложении можно заполнить свойства объекта CultureAndRegionInfoBuilder существующим объектом CultureInfo и методом LoadDataFromCultureInfo, а также существующим объектом RegionInfo и методом LoadDataFromRegionInfo. В случае замены языков и региональных параметров свойства объекта CultureAndRegionInfoBuilder автоматически заполняются свойствами заменяемого языка и региональных параметров.

  2. Приложение изменяет свойства объекта CultureAndRegionInfoBuilder в соответствии с потребностями.

  3. Для регистрации пользовательского языка и региональных параметров приложение вызывает метод Register. В процессе регистрации выполняются действия, перечисленные ниже.

    • Создается NLP-файл, который содержит сведения, определенные в объекте CultureAndRegionInfoBuilder.

    • NLP-файл сохраняется в системном каталоге %WINDIR%\Globalization, благодаря чему сведения о языке и региональных параметрах сохраняются на компьютере и при его выключении. Поскольку NLP-файл сохраняется в системном каталоге, на компьютер, где регистрируется пользовательский язык и региональные параметры, необходимо войти с учетной записью администратора.

    • Выполняется настройка платформы .NET Framework для поиска при следующем запросе на создание нового пользовательского языка и региональных параметров в системном каталоге %WINDIR%\Globalization, а не во внутреннем кэше.

    Теперь пользовательский язык и региональные параметры обладают таким же статусом, как любой предопределенный язык и региональные параметры платформы .NET Framework или языковой стандарт Windows на компьютере. Пользовательский язык и региональные параметры будут доступны, пока приложение не удалит с компьютера соответствующий NLP-файл с помощью метода Unregister.

  4. Имя пользовательского языка и региональных параметров определяется в приложении в конструкторе класса CultureInfo.

Пример

В примере, приведенном ниже, для определения и регистрации пользовательского языка и региональных параметров с именем "x-en-US-sample" используется класс CultureAndRegionInfoBuilder, а затем для этого пользовательского языка и региональных параметров создается объект CultureInfo. Кроме того, в примере показаны некоторые соответствующие свойства объектов CultureAndRegionInfoBuilder и CultureInfo.

' This example demonstrates the System.Globalization.Culture-
' AndRegionInfoBuilder Register method.
' Compile this code example with a reference to sysglobl.dll.

Imports System
Imports System.Globalization

Class Sample
    Public Shared Sub Main() 
        Dim cib As CultureAndRegionInfoBuilder = Nothing
        Try
            ' Create a CultureAndRegionInfoBuilder object named "x-en-US-sample".
            Console.WriteLine("Create and explore the CultureAndRegionInfoBuilder..." & vbCrLf)
            cib = New CultureAndRegionInfoBuilder("x-en-US-sample", CultureAndRegionModifiers.None)

            ' Populate the new CultureAndRegionInfoBuilder object with culture information.
            Dim ci As New CultureInfo("en-US")
            cib.LoadDataFromCultureInfo(ci)

            ' Populate the new CultureAndRegionInfoBuilder object with region information.
            Dim ri As New RegionInfo("US")
            cib.LoadDataFromRegionInfo(ri)

            ' Display some of the properties of the CultureAndRegionInfoBuilder object.
            Console.WriteLine("CultureName:. . . . . . . . . . {0}", cib.CultureName)
            Console.WriteLine("CultureEnglishName: . . . . . . {0}", cib.CultureEnglishName)
            Console.WriteLine("CultureNativeName:. . . . . . . {0}", cib.CultureNativeName)
            Console.WriteLine("GeoId:. . . . . . . . . . . . . {0}", cib.GeoId)
            Console.WriteLine("IsMetric: . . . . . . . . . . . {0}", cib.IsMetric)
            Console.WriteLine("ISOCurrencySymbol:. . . . . . . {0}", cib.ISOCurrencySymbol)
            Console.WriteLine("RegionEnglishName:. . . . . . . {0}", cib.RegionEnglishName)
            Console.WriteLine("RegionName: . . . . . . . . . . {0}", cib.RegionName)
            Console.WriteLine("RegionNativeName: . . . . . . . {0}", cib.RegionNativeName)
            Console.WriteLine("ThreeLetterISOLanguageName: . . {0}", cib.ThreeLetterISOLanguageName)
            Console.WriteLine("ThreeLetterISORegionName: . . . {0}", cib.ThreeLetterISORegionName)
            Console.WriteLine("ThreeLetterWindowsLanguageName: {0}", cib.ThreeLetterWindowsLanguageName)
            Console.WriteLine("ThreeLetterWindowsRegionName: . {0}", cib.ThreeLetterWindowsRegionName)
            Console.WriteLine("TwoLetterISOLanguageName: . . . {0}", cib.TwoLetterISOLanguageName)
            Console.WriteLine("TwoLetterISORegionName: . . . . {0}", cib.TwoLetterISORegionName)
            Console.WriteLine()

            ' Register the custom culture.
            Console.WriteLine("Register the custom culture...")
            cib.Register()

            ' Display some of the properties of the custom culture.
            Console.WriteLine("Create and explore the custom culture..." & vbCrLf)
            ci = New CultureInfo("x-en-US-sample")

            Console.WriteLine("Name: . . . . . . . . . . . . . {0}", ci.Name)
            Console.WriteLine("EnglishName:. . . . . . . . . . {0}", ci.EnglishName)
            Console.WriteLine("NativeName: . . . . . . . . . . {0}", ci.NativeName)
            Console.WriteLine("TwoLetterISOLanguageName: . . . {0}", ci.TwoLetterISOLanguageName)
            Console.WriteLine("ThreeLetterISOLanguageName: . . {0}", ci.ThreeLetterISOLanguageName)
            Console.WriteLine("ThreeLetterWindowsLanguageName: {0}", ci.ThreeLetterWindowsLanguageName)

            Console.WriteLine(vbCrLf & "Note:" & vbCrLf & "Use the example in the " & _
                              "Unregister method topic to remove the custom culture.")
        Catch e As Exception
            Console.WriteLine(e)
        End Try

    End Sub 'Main
End Class 'Sample

'This code example produces the following results:
'
'Create and explore the CultureAndRegionInfoBuilder...
'
'CultureName:. . . . . . . . . . x-en-US-sample
'CultureEnglishName: . . . . . . English (United States)
'CultureNativeName:. . . . . . . English (United States)
'GeoId:. . . . . . . . . . . . . 244
'IsMetric: . . . . . . . . . . . False
'ISOCurrencySymbol:. . . . . . . USD
'RegionEnglishName:. . . . . . . United States
'RegionName: . . . . . . . . . . x-en-US-sample
'RegionNativeName: . . . . . . . United States
'ThreeLetterISOLanguageName: . . eng
'ThreeLetterISORegionName: . . . USA
'ThreeLetterWindowsLanguageName: ENU
'ThreeLetterWindowsRegionName: . USA
'TwoLetterISOLanguageName: . . . en
'TwoLetterISORegionName: . . . . US
'
'Register the custom culture...
'Create and explore the custom culture...
'
'Name: . . . . . . . . . . . . . x-en-US-sample
'EnglishName:. . . . . . . . . . English (United States)
'NativeName: . . . . . . . . . . English (United States)
'TwoLetterISOLanguageName: . . . en
'ThreeLetterISOLanguageName: . . eng
'ThreeLetterWindowsLanguageName: ENU
'
'Note:
'Use the example in the Unregister method topic to remove the custom culture.
'
// This example demonstrates the System.Globalization.Culture-
// AndRegionInfoBuilder Register method.
// Compile this code example with a reference to sysglobl.dll.

using System;
using System.Globalization;

class Sample 
{
    public static void Main() 
    {
    CultureAndRegionInfoBuilder cib = null;
    try 
    {
// Create a CultureAndRegionInfoBuilder object named "x-en-US-sample".
    Console.WriteLine("Create and explore the CultureAndRegionInfoBuilder...\n");
    cib = new CultureAndRegionInfoBuilder(
                         "x-en-US-sample", CultureAndRegionModifiers.None);

// Populate the new CultureAndRegionInfoBuilder object with culture information.
    CultureInfo ci = new CultureInfo("en-US");
    cib.LoadDataFromCultureInfo(ci);

// Populate the new CultureAndRegionInfoBuilder object with region information.
    RegionInfo  ri = new RegionInfo("US");
    cib.LoadDataFromRegionInfo(ri);

// Display some of the properties of the CultureAndRegionInfoBuilder object.
    Console.WriteLine("CultureName:. . . . . . . . . . {0}", cib.CultureName);
    Console.WriteLine("CultureEnglishName: . . . . . . {0}", cib.CultureEnglishName);
    Console.WriteLine("CultureNativeName:. . . . . . . {0}", cib.CultureNativeName);
    Console.WriteLine("GeoId:. . . . . . . . . . . . . {0}", cib.GeoId);
    Console.WriteLine("IsMetric: . . . . . . . . . . . {0}", cib.IsMetric);
    Console.WriteLine("ISOCurrencySymbol:. . . . . . . {0}", cib.ISOCurrencySymbol);
    Console.WriteLine("RegionEnglishName:. . . . . . . {0}", cib.RegionEnglishName);
    Console.WriteLine("RegionName: . . . . . . . . . . {0}", cib.RegionName);
    Console.WriteLine("RegionNativeName: . . . . . . . {0}", cib.RegionNativeName);
    Console.WriteLine("ThreeLetterISOLanguageName: . . {0}", cib.ThreeLetterISOLanguageName);
    Console.WriteLine("ThreeLetterISORegionName: . . . {0}", cib.ThreeLetterISORegionName);
    Console.WriteLine("ThreeLetterWindowsLanguageName: {0}", cib.ThreeLetterWindowsLanguageName);
    Console.WriteLine("ThreeLetterWindowsRegionName: . {0}", cib.ThreeLetterWindowsRegionName);
    Console.WriteLine("TwoLetterISOLanguageName: . . . {0}", cib.TwoLetterISOLanguageName);
    Console.WriteLine("TwoLetterISORegionName: . . . . {0}", cib.TwoLetterISORegionName);
    Console.WriteLine();

// Register the custom culture.
    Console.WriteLine("Register the custom culture...");
    cib.Register();

// Display some of the properties of the custom culture.
    Console.WriteLine("Create and explore the custom culture...\n");
    ci = new CultureInfo("x-en-US-sample");

    Console.WriteLine("Name: . . . . . . . . . . . . . {0}", ci.Name);
    Console.WriteLine("EnglishName:. . . . . . . . . . {0}", ci.EnglishName);
    Console.WriteLine("NativeName: . . . . . . . . . . {0}", ci.NativeName);
    Console.WriteLine("TwoLetterISOLanguageName: . . . {0}", ci.TwoLetterISOLanguageName);
    Console.WriteLine("ThreeLetterISOLanguageName: . . {0}", ci.ThreeLetterISOLanguageName);
    Console.WriteLine("ThreeLetterWindowsLanguageName: {0}", ci.ThreeLetterWindowsLanguageName);

    Console.WriteLine("\nNote:\n" +
        "Use the example in the Unregister method topic to remove the custom culture.");
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
    }
    }
}
/*
This code example produces the following results:

Create and explore the CultureAndRegionInfoBuilder...

CultureName:. . . . . . . . . . x-en-US-sample
CultureEnglishName: . . . . . . English (United States)
CultureNativeName:. . . . . . . English (United States)
GeoId:. . . . . . . . . . . . . 244
IsMetric: . . . . . . . . . . . False
ISOCurrencySymbol:. . . . . . . USD
RegionEnglishName:. . . . . . . United States
RegionName: . . . . . . . . . . x-en-US-sample
RegionNativeName: . . . . . . . United States
ThreeLetterISOLanguageName: . . eng
ThreeLetterISORegionName: . . . USA
ThreeLetterWindowsLanguageName: ENU
ThreeLetterWindowsRegionName: . USA
TwoLetterISOLanguageName: . . . en
TwoLetterISORegionName: . . . . US

Register the custom culture...
Create and explore the custom culture...

Name: . . . . . . . . . . . . . x-en-US-sample
EnglishName:. . . . . . . . . . English (United States)
NativeName: . . . . . . . . . . English (United States)
TwoLetterISOLanguageName: . . . en
ThreeLetterISOLanguageName: . . eng
ThreeLetterWindowsLanguageName: ENU

Note:
Use the example in the Unregister method topic to remove the custom culture.

*/

См. также

Ссылки

CultureInfo

CultureAndRegionInfoBuilder

CultureAndRegionModifiers

Другие ресурсы

Шифрование и локализация