Utilisation de la classe CultureInfo

[Cette documentation constitue un aperçu et pourra faire l'objet de modifications dans les versions ultérieures. Des rubriques vierges sont incluses en tant qu'espaces réservés.]

La CultureInfo contient des informations spécifiques à la culture, telles que la langue, le pays/la région, le calendrier et les conventions culturelles associées à une culture spécifique. Cette classe fournit aussi les informations requises pour effectuer des opérations spécifiques à la culture, par exemple le choix de la casse, la mise en forme des dates et des nombres ou la comparaison des chaînes.

La classe CultureInfo indique un nom unique pour chaque culture. Pour plus d'informations sur les noms de cultures, consultez la description de la classe CultureInfo. Votre application peut utiliser la méthode GetCultures pour récupérer la liste complète de toutes les cultures. L'exemple suivant affiche la liste de toutes les cultures.

Imports System.Globalization

Public Class Example
   Public Shared Sub Main()  
      For Each ci As CultureInfo In CultureInfo.GetCultures(CultureTypes.AllCultures)
         Console.WriteLine(ci)
      Next
   End Sub
End Class
using System;
using System.Globalization;

public class printClass
{
   public static void Main()
   {
      foreach (CultureInfo ci in CultureInfo.GetCultures(CultureTypes.AllCultures))
      {
         Console.WriteLine(ci);
      }
   }
}

Utilisation de CultureInfo avec du code non managé

Notes

Les applications .NET Framework peuvent accéder aux fonctions non managées dans les bibliothèques de liens dynamiques à l'aide du service Présentation détaillée de l'appel de code non managé.

Pour initialiser des informations de pays/région, votre application peut passer un objet CultureInfo à un objet RegionInfo qui correspond au pays/région. Dans le code non managé, l'application peut également passer un objet CultureInfo à la fonction Win32 GetLocaleInfo.

Pour initialiser un objet RegionInfo à l'aide d'un objet CultureInfo, votre application doit spécifier un objet CultureInfo qui représente une culture spécifique, telle que Arabe (Algérie) nommé « ar-DZ ». Si vous tentez d'initialiser un objet RegionInfo avec un objet CultureInfo représentant une culture neutre telle que pour Arabe « ar »), une exception est levée. La culture neutre n'indique pas les informations de région ou de pays nécessaires au mappage sur un pays ou une région.

La fonction GetLocaleInfo est différente du constructeur RegionInfo, car elle retourne un pays ou une région pour un objet CultureInfo qui représente une culture spécifique ou une culture neutre. Par exemple, si l'application passe un objet CultureInfo qui représente la culture neutre Arabe à GetLocaleInfo, la méthode mappe la culture neutre sur le pays ou la région par défaut auquel ou à laquelle elle est associée. Dans ce cas, GetLocaleInfo retourne Arabie Saoudite. Soyez prudent lorsque vous utilisez la méthode GetLocaleInfo, car le mappage par défaut du pays ou la région proposé peut être culturellement inadéquat pour votre application. Pour éviter cette différence, votre application doit uniquement utiliser des cultures spécifiques lors de l'interopérabilité avec une fonction API.

L'exemple suivant montre comment le constructeur de classe RegionInfo et la méthode GetLocaleInfo peuvent récupérer des valeurs différentes en cas de passage du même objet CultureInfo. Remarquez que lorsque l'objet CultureInfo représente la culture spécifique Arabe (Algérie), les deux méthodes récupèrent Algérie comme nom de pays ou de région. Cependant, lorsque l'objet CultureInfo représente la culture neutre Arabe, les résultats sont différents. Le constructeur d' RegionInfo ne récupère pas un pays/région, tandis que GetLocaleInfo retourne Arabie Saoudite.

Imports System.Globalization
Imports System.Runtime.InteropServices

Module CountryRegionName
   ' The name of a country or region in English.
   Private LOCALE_SENGCOUNTRY As Integer = &H1002

   ' Use COM interop to call the Win32 API GetLocalInfo.
   Declare Unicode Function GetLocaleInfoW Lib "Kernel32.dll" _
      (Locale As Integer, LCType As Integer,<[In](), _
       MarshalAs(UnmanagedType.LPWStr)> lpLCData As String, _
       cchData As Integer) As Integer

   ' A method to retrieve the .NET Framework Country/Region
   ' that maps to the specified CultureInfo.
   Public Function GetNetCountryRegionName(ci As CultureInfo) As String
      ' If the specified CultureInfo represents a specific culture,
      ' the attempt to create a RegionInfo succeeds.
      Try
         Dim ri As New RegionInfo(ci.LCID)
         Return ri.EnglishName
         ' Otherwise, the specified CultureInfo represents a neutral
         'culture, and the attempt to create a RegionInfo fails.
      Catch
         Return String.Empty
      End Try
   End Function

   ' A method to retrieve the Win32 API Country/Region
   ' that maps to the specified CultureInfo.
   Public Function GetWinCountryRegionName(ci As CultureInfo) As String
      Dim size As Integer = GetLocaleInfoW(ci.LCID, _
         LOCALE_SENGCOUNTRY, Nothing, 0)
      Dim str As New String(" "c, size)
      Dim err As Integer = GetLocaleInfoW(ci.LCID, _
         LOCALE_SENGCOUNTRY, str, size)
      ' If the string is not empty, GetLocaleInfoW succeeded.
      ' It will succeed regardless of whether ci represents
      ' a neutral or specific culture.
      If err <> 0 Then
         Return str
      Else
         Return String.Empty
      End If
   End Function

   Public Sub Main()
      ' Create a CultureInfo initialized to the neutral Arabic culture.
      Dim ci1 As New CultureInfo("ar")
      Console.WriteLine(ControlChars.NewLine + _
         "The .NET Region name: {0}", _
          GetNetCountryRegionName(ci1))
      Console.WriteLine("The Win32 Region name: {0}", _
         GetWinCountryRegionName(ci1))

      ' Create a CultureInfo initialized to the specific 
      ' culture Arabic in Algeria.
      Dim ci2 As New CultureInfo("ar-DZ")
      Console.WriteLine(ControlChars.NewLine + _
         "The .NET Region name: {0}", _
         GetNetCountryRegionName(ci2))
      Console.WriteLine("The Win32 Region name: {0}", _
         GetWinCountryRegionName(ci2))
   End Sub
End Module
' The example displays the following output:
'   The .NET Region name:
'   The Win32 Region name: Saudi Arabia
'
'   The .NET Region name: Algeria
'   The Win32 Region name: Algeria
using System;
using System.Globalization;
using System.Runtime.InteropServices;

class CountryRegionName
{
   // The name of a country or region in English
   const int LOCALE_SENGCOUNTRY     = 0x1002;

   // Use COM interop to call the Win32 API GetLocalInfo.
   [DllImport("kernel32.dll", CharSet=CharSet.Unicode)]
   public static extern int GetLocaleInfo(
      // The locale identifier.
      int Locale,
      // The information type.
      int LCType,
      // The buffer size.
      [In, MarshalAs(UnmanagedType.LPWStr)] string lpLCData,int cchData
   );

   // A method to retrieve the .NET Framework Country/Region
   // that maps to the specified CultureInfo.
   static String GetNetCountryRegionName(CultureInfo ci)
   {
      // If the specified CultureInfo represents a specific culture,
      // the attempt to create a RegionInfo succeeds.
      try
      {
         RegionInfo ri = new RegionInfo(ci.LCID);
         return ri.EnglishName;
      }
      // Otherwise, the specified CultureInfo represents a neutral
      // culture, and the attempt to create a RegionInfo fails.
      catch
      {
         return String.Empty;
      }
   }

   // A method to retrieve the Win32 API Country/Region
   // that maps to the specified CultureInfo.
   static String GetWinCountryRegionName(CultureInfo ci)
   {
      int size = GetLocaleInfo(ci.LCID, LOCALE_SENGCOUNTRY, null, 0);
      String str = new String(' ', size);
      int err  = GetLocaleInfo(ci.LCID, LOCALE_SENGCOUNTRY, str, size);
      // If the string is not empty, GetLocaleInfo succeeded.
      // It will succeed regardless of whether ci represents
      // a neutral or specific culture.
      if(err != 0)  
         return str;
      else
         return String.Empty;
   }

   static void Main()
   {
      // Create a CultureInfo initialized to the neutral Arabic culture.
      CultureInfo ci1 = new CultureInfo("ar");  
      Console.WriteLine("\nThe .NET Region name: {0}", 
         GetNetCountryRegionName(ci1));
      Console.WriteLine("The Win32 Region name: {0}",
         GetWinCountryRegionName(ci1));

      // Create a CultureInfo initialized to the specific 
      // culture Arabic in Algeria.
      CultureInfo ci2 = new CultureInfo(0x1401);  
      Console.WriteLine("\nThe .NET Region name: {0}", 
         GetNetCountryRegionName(ci2));
      Console.WriteLine("The Win32 Region name: {0}",
         GetWinCountryRegionName(ci2));
   }
}
// The example displays the following output:
//   The .NET Region name:
//   The Win32 Region name: Saudi Arabia
//
//   The .NET Region name: Algeria
//   The Win32 Region name: Algeria

Voir aussi

Référence

CultureInfo

Concepts

Utilisation de la propriété CurrentCulture

Utilisation de la propriété InvariantCulture

Autres ressources

Entraînerait et localisation des applications.NET Framework