Wednesday, July 25, 2012

Using Resource Files in ASP.NET

There are 2 types of resource files, local and global resource files.  Local resource files are used for a specific page, while global resources can be used throughout a site.

Local Resource files


Local resource files must be stored in the ASP.NET folder App_LocalResources.  These files have the extension .resx and must be named like the page.  If the page is named About.aspx, then the resource page will be About.aspx.resx.  This will be the default resource file for the page.  In order to create a resource file for another language, you will need to create another file with the language 2 letter ISO code.  If you need resources for the German language for example, the file will need to be named About.aspx.de.resx.  You can also use specific languages like About.aspx.en-GB.resx

Implicit Localization


To easiest way to create a resource file, is to use the tool provided in Visual Studio. From the Tools menu, select Generate Local Resource.  This will create a resource file for the form you are viewing.

The tool will generate resource keys for every string property for every control


Explicit Localization


In explicit localization, you can manually attach a resource to a control's property like so

 

Global Resource files


Global resource files are stored in the App_GlobalResources ASP.NET folder.  Use these resources for text which will be used more than once in your website.  I typically use it for common words such as 'Save', 'Edit', 'Delete', etc.. These files also have the .resx extension.  In order to use them from mark up, use the same syntax as the explicit localization mentioned above


Using and accessing resources programmatically


There are 2 ways to retrieve values at runtime.  If the global resources are available in your project you can use the following syntax which also provides intellisense
string myText = Resources.SharedLocalizedText.WelcomeText;
If the file is not available at design time, you can use the following method
string myText = Convert.ToString(GetGlobalResourceObject("MyGlobalResourceFile", "WelcomeText"));

The first parameter is the name of the global resource file (without the extension) and the second is the resource key which you want to retrieve from the file

2 comments:

  1. The blog gave me idea about Using Resource Files in ASP.NET My sincere thanks for sharing this post Please Continue to share this kind of post
    Dot Net Training in Chennai

    ReplyDelete
  2. nice blog has been shared by you. before i read this blog i didn't have any knowledge about this but now i got some knowledge. so keep on sharing such kind of an interesting blogs.
    dot net training in chennai

    ReplyDelete