what is Resource Files?

来源:互联网 发布:淘宝店铺金牌卖家 退货 编辑:程序博客网 时间:2024/05/31 19:48

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

As well as culture specific applications, resource files can also be used to create a branded or more specialised instance of an application. For example, you can create a generalised application and use resource files and satellite assemblies to create customer branded or specific applications without recompiling the application.

Resources can be added to a project from the “Add new item” menu. Select Resources File and give it a meaningful name. You can open the resource file from the solution explorer which will open the resource editor. From here you 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.

In this example I am going to create a simple hello world application loading the text from the resource file. Create a new console application and add a new resource file called applicationResources.resx. In the strings section of the newly created file create a key called “Hello” with a value of “Hello World”.

Resource files are strongly typed meaning that we can programmatically reference the keys by name, rather than hard coding the name in a string. To access the Hello World string we can use the following code:

using System;using System.Text; class Program{  static void Main(string[] args)  {    Console.WriteLine(applicationResources.Hello);  }}


 

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. If you hard coded the name you would have to search and replace followed by testing to make sure that every instance of the incorrect key name was fixed.

Resources can hold many different types, including Bitmap images. In the resource editor you can change the type of resource from the drop down list. The strongly typed resources will return an object of the correct class when you access the key. When you access a string it will return a string object and when you access an image it will return a Bitmap object.

Bitmap bmp = applicationStringResources.MyLogo;


 

Assemblies can be individually compiled into DLL satellite assemblies which can be dropped into the application directory or globalassembly cache so they can be used at runtime using the ResourceManager. The process of creating and using satellite assemblies is described in more detail in the Creating and Implementing Satellite Assemblies tutorial.

 

原创粉丝点击