Localization Like the Pros—Using XML Resource Files

Jump to: navigation, search
Visual C# Tutorials

Localize Like the Pros

© 2004 Wiley Publishing, Inc.

Using XML Resource Files

With the resgen command, we create XML resources out of the text-based resource files:

resgen welcome.txt welcome.resx
resgen welcome.de.txt welcome.de.resx
resgen welcome.fr.txt welcome.fr.resx

The generated XML-based resource files are then added to the project by selecting Add -> Add Existing Item in the Solution Explorer. Similar to binary resource files, the BuildAction for .resx files is set to Embedded Resource. When building the project, the resources are added to the satellite assemblies.

Now there are two .mresource entries in the satellite assembly as can be seen in Figure 17-18—the resource Wrox.ProCSharp.Localization.BookOfTheDayForm.de was originally created with the Windows Forms designer, and Wrox.ProCSharp.Localization.Welcome.de is the resource from the new Welcome.de.resx resource file.


Image:557599fg1718.jpg
Figure 17-18


Of course, the source code of the method WelcomeMessage() must also be changed to use the resources. A ResourceManager instance is created to get the resource named Wrox.ProCSharp.Assemblies .Localization.Welcome from the current assembly. With this resource manager, you get the resources we created previously in the resource files using GetString() methods. For the ResourceManager class, you have to declare the use of the System.Resources namespace; the Assembly class is in the System.Reflection namespace.

public void WelcomeMessage()
      {
 
         ResourceManager resource = 
            new ResourceManager("Wrox.ProCSharp.Localization.Welcome", 
                                Assembly.GetExecutingAssembly());
         DateTime now = DateTime.Now;
         string message;
         if (now.Hour <= 12)
         {
 
            message = resource.GetString("Good Morning");
         }
         else if (now.Hour <= 19)
         {
 
            message = resource.GetString("Good Afternoon");
         }
         else
         {
 
            message = resource.GetString("Good Evening");
         }
         MessageBox.Show(message + "\nThis is a localization sample");
      }

When the program is started using English, German, or French you will get the message boxes shown in Figures 17-19, 17-20 and 17-21.


Image:557599fg1719.jpg
Figure 17-19


Image:557599fg1720.jpg
Figure 17-20


Image:557599fg1721.jpg
Figure 17-21


prevpp.png  nextpp.png
C# Online.NET