Resource files in Visual Studio

Resource files can be added to a project in Visual Studio.  These are xml based text files which contain key-value pairs.  When the resource files are saved, source code will be automatically generated that can be compiled like any other C# or VB file.  It is advisable to put the resource files into a separate project so that they are contained within a common namespace.

Referencing your resources in MVC

After the resource files have been compiled they can be accessed like any other static property.  So the razor syntax would look like this:

<h1>@MyRources.Form.Heading</h1>

These resources can also be accessing in the code (C#, VB etc) just like any other property.

Creating Multi-culture Applications with Resource Files

The name of the resource file is used to determine which culture it will represent.  If a file is created without any suffix it will contain the default or fall back values.  For example if you have a number of resource files like this;

  • Form.resx
  • Form.en.resx
  • Form.en-gb.resx
  • Form.en-us.resx

This means that if your current thread culture does not match any of the available resources (i.e. it’s not English language) then the values from Form.resx will be used.  If the current thread culture uses the english language but the culture is not UK or USA (eg. Australian) then Form.en.resx will be used.  Form.en-gb specifies the language (English) and culture (UK) so it could contain culture specific terms.

This approach provides a comprehensive solution for multi-culture resources however it will create a lot of copy and paste type work.  Each resource file should contain an entry for every key value in the resource otherwise the default value will be used.  It would be nice to have a tool which does some of this work automatically although I have not yet found one that does a good job*.  There are some which will provide a web interface to alter the resource files however I have not tried these.

* A tool for creating resource files should be easy to set-up otherwise the time required to set-up the tool will be more than the time of altering the files manually.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s