Saturday, July 5, 2008

Creating a Custom Culture in .NET Framework

Another interesting topic on cultures in .NET Framework is creating a custom culture. This is very useful if the predefined cultures in .NET Framework or the underlying windows operating system do not provide the required information.

The CultureAndRegionInfoBuilder class allows the creating of custom cultures from scratch or based on existing cultures.

For instance, if we try to create a CultureInfo object for "en-MU", an exception is thrown.

CultureInfo muCultureInfo = new CultureInfo("en-MU");



I will now create this custom "en-MU" culture by using the existing cultures.

Step 1: Add a reference to sysglobl.dll in the project. This library can be found in the Microsoft .NET folder (e.g. C:\Windows\Microsoft.NET\Framework\v2.0.50727\).

Step 2: Add the namespaces System and System.Globalization

using System;
using System.Globalization;

Step 3: Create an instance of the CultureAndRegionInfoBuilder

CultureAndRegionInfoBuilder infoBuilder
= new CultureAndRegionInfoBuilder("en-MU", CultureAndRegionModifiers.None);


The CultureAndRegionModifiers.None is used since the custom culture is a specific one. More information about the CultureAndRegionModifiers enumeration here.

Step 4: To keep the new custom culture simple, I will use a combination of the existing en-GB and fr-FR cultures. Hence, in this step, the culture and region details will be loaded in the new culture.

CultureInfo frCulture = new CultureInfo("fr-FR");
CultureInfo gbCulture = new CultureInfo("en-GB");
infoBuilder.LoadDataFromCultureInfo(frCulture);
infoBuilder.LoadDataFromRegionInfo(new RegionInfo(gbCulture.LCID));

Step 5: The new custom culture is now ready. However, additional details can be further changes to have more precise information.

For example,

infoBuilder.CultureEnglishName = "Mauritius";
infoBuilder.CurrencyEnglishName = "Mauritian Rupees";
infoBuilder.TwoLetterISORegionName = "MU";
infoBuilder.NumberFormat.CurrencySymbol = "Rs";


Step 6: Register the new custom culture on the local computer and makes the culture available to the application(s).

infoBuilder.Register();



Now, the culture "en-MU" can be successfully instantiated.

CultureInfo muCultureInfo = new CultureInfo("en-MU");



Note: To unregister the custom culture, the Unregister() method can be used.

CultureAndRegionInfoBuilder.Unregister("en-MU");

No comments: