Saturday, September 11, 2010

C#.net - Read the Resource file (.resx)

Resource files are used to hold files associated with the application, such as String,images, sounds and other data objects. Resource files can also be used to localise applications to specific cultures.

Let see how to create a Reosurce file in project.

Step 1

Create a console application and give name it ConResource.

Step 2
Create a resource file in a console application,Right click on application from solution explorer, select Add New Item,Select Resources File from installed Visual Studio templates and name it MyResource,it is look like this
















Click on image for better view


Step 3
After creating a resource file,Resource editor will be open,it is look like this

















Click on image for better view



Step 4
In Resource Editor,we can add string resources, images, icons, audio, general files and other documents. Resource files are simple key/value combination with a comment and are stored as XML,it is look like this

Click on image for better view

In String Section create a two key(Name) called as FirstName and LastName with value 'kishor' and 'Naik'.
Resource files are strongly typed meaning that we can programmatically reference the keys by name, rather than hard coding the name in a string.

Step 5
Read a value from Resources file,it is look like this



class Program
    {
        static void Main(string[] args)
        {
            //// Read a value from Resource File

            System.Console.WriteLine("First Name\t:\t" + MyResource.FirstName.Trim());
            System.Console.WriteLine("Last Name\t:\t" + MyResource.LastName.Trim());   
        }
    }

There are two main advantages to using strongly typed resource names. Firstly its easier to let IntelliSense build up the reference, and secondly, should you change the key name, the application will not compile – you know exactly where to update the code.

Run the project.

Note - Resources file can be used in Window Application,WPF and Web application.

Download
Download Source Code

1 comment:

  1. Kishor, if you're interested in localization tools that help manage app translation smoother, check out the l10n platform https://poeditor.com

    I think it's an awesome online & collaborative solution.

    ReplyDelete