Resource files in C#
Resource files are files that can hold resources like images, strings, icons, audio files, etc. These are xml files with the extension .resx. They are mainly helpful when the application uses images and NLS (Native Language Strings). To add and use a resource file in your application follow the steps.
- Right click on the Project from the Solution folder and select Add > New Item > Resource File.
- Enter an appropriate name for the file and click on Add.
- Your resource file is now created.
To add some strings to the resource files,
- Double click on the resource file to get the String table
- Enter the ID for a string and its corresponding value on the other field
- Save the resource file
You can also add images to the resource file by pressing Ctrl + 2, icons by pressing Ctrl + 3 and so on
To use it in the application
- Create an object of the ResourceManager class under the namespace System.Resources.ResourceManager
- To its constructor pass the arguments as, <namespace>.<classname> of the resource file as the first argument (If you are unaware of the resource file’s class name, then open the resource file’s designer.cs. Mostly it will be an internal class) and <assembly> of the namespace as the second argument. If it is in the same assembly then, typeof(<classname>.Assembly)
- Now you have created an object of the resource file
- To get the value of a string ID, you can use <resource object>.GetString( <stringID> )
For example,
using System.Resources;
ResourceManager stringTable = new ResourceManager(“Workspace.Resource”, typeof(Resource).Assembly);
MessageBox.Show(stringTable.GetString(“FOO”));
The above snippet will get the value of the string FOO from the stringTable (Resource file)