Creating and Using Resource Files

Creating and Using Resource Files

Resource files are used in .NET to store culture-specific data all in one place, separate from the code. For example, suppose you are developing a multi-language Web site and you have a form on a page with a label beside a text field and the label in English says “First Name.” Instead of having code like this:

if (language == "English") {   lblFirstName = "First Name";}else if (language == "German") {   lblFirstName = "Vorname";}

You can just do this:

ResourceManager resourceManager = new ResourceManager("nameSpace.resourceFileBaseName",Assembly.GetExecutingAssembly());lblFirstName = resourceManager.GetString("lblFirstName");

And that’s it?just two lines. There’s no need to change a million sections of code each time you add or take away a language.

So, what do the parameters mean? The first parameter to ResourceManager’s constructor is the location of the resource file to use. This parameter consists of two parts: the first part is the namespace in which the resource file belongs and the second is the base name of the resource file to use.

The second parameter gets the executing assembly from which the culture information is read and used in combination with the base name to decide which resource file to use. So, if the culture is de (German) then the German resource file is used.

The parameter in the GetString method is the key into the resource file. The resource file contains two fields of interest: name and value. In the German file, you would have this in the resource file:

name         valuelblFirstName Vorname

So when you pass lblFirstName into the GetString method, you get back Vorname in the case when you are using the German site.


Share the Post: