Introduction
In this article, I will give you a small example of how to add and use resources. This tutorial consists of two classes; one to create the resource and one that uses it.
The System.Resources is a very useful namespace that allows you to create and store culture-specific resources used in an application (for example, you can have Spanish and English resources). Resources allows you to place culture-specific items inside satellite files, rather than directly in your main application. This aspect can dramatically improve reusability of your code. One does not need to recompile the code in order to change the resource.
Recently, I have found another useful way to use resources. Unless an images is already loaded into memory, whenever you do a mouseover you need to read the image from file.
For example: myLabel.Image = Image.FromFile("image.jpg");
If you have a big application, the system is slow, or you need to load big images, the image can take a few moments to load up, and will give you a delay. However, if the images is in a resource file, the change will be almost instantaneous.
Creating the Resource File:
To create a resource file, create an instance of ResourceWriter and pass it the name of the resource file you want to create as a string.
ResourceWriter myResource =new ResourceWriter("Images.resources");
Now add your image to the resource file by using the AddResource method and pass it the name of the image and the image as the parameters.
myResource.AddResource(fileName, new Bitmap(files[i]));
Alternately, you can use the overloaded AddResource method to pass it a string as the value.
myResource.AddResource("MyResourceName", "My Resource Value");
Once you have added everything you want to the resource file, call the Close() method. This will implicitly call the Generate() method (which will save the resources to the output stream) and then closes the file.
myResource.Close();
Using Resources:
The first thing you need to do in order to use the Images.resources file in your code is add it to your project. In VS.NET, right-click on your project, select Add Existing Item and add your resource file. This will add the file as an Embedded Resource.
Use ResourceManager to access and control the resources.
private System.Resources.ResourceManager rm = new System.Resources.ResourceManager("ResourceClient.Images",System.Reflection.Assembly.GetExecutingAssembly());
Now you can easily retrieve your specific objects and strings by using the GetObject and GetString methods.
lblCancel.Image = (Image)rm.GetObject("cancel-on.png");
this.lblResource.Text = rm.GetString("MyResourceName");