1. Resource Basics
(1) Manifest Resources
Resources are added to the assembly during compilation. If you want to embed resources into an assembly, you must add the file to the project and the file is automatically copied to the Resources folder of the project folder. If you want to embed into an assembly, you also need to select the file and modify its attribute "Build Action" to "Embed Resource", which defaults to "Content".
Once set to an embedded resource, it becomes part of the assembly in the resource inventory. Each assembly, whether static or dynamic, contains a collection of data that describes how elements of the assembly are associated with each other. The assembly manifest contains these assembly metadata. The assembly manifest contains all metadata required to specify the version requirements and security identifier of the assembly, as well as all metadata required to define the scope of the assembly and to parse references to resources and classes.
(2) Naming Mainfest Resources
To view a file that has been correctly embedded into the project output assembly, you can use the SDK tool, which is actually the MSIL disassembler, which can display all embedded resources in the Mainfest view of your assembly.
It is displayed as a .mresource entry in ildasm, and the resource name display format is as follows:
defaultNamespace can be changed in the "Applications" tab page in the project's properties page.
(3) Loading Mainfest Resources
The list is also enumerated through the program, and the GetMainifestResourceNames method of the class needs to be utilized. In addition, you can also retrieve specific types of assembly. For example, the Assembly class also provides GetAssembly, GetCallingAssembly, GetEntryAssembly, GetExecutingAssembly, etc.
// Get this type's assembly Assembly asm =().Assembly; // Enumerate the assembly's manifest resources foreach( string resourceName in () ){ (resourceName); }
Type is the root of the function and is also the main way to access metadata. Use members of Type to get information about type declarations, such as constructors, methods, fields, properties, and events for classes, as well as modules and assemblies where the class is deployed.
Indicates that a certain type is the only Type object; that is, two Type objects refer to the same object if and only if they represent the same type. This allows reference equations to be used to compare Type objects. Type class represents type declarations: class type, interface type, array type, value type, enum type, type parameter, generic type definition, and open or closed constructed generic types. Method returns a Type object representing the instance type.
If you know the name of the resource, you can load the specified manifest resource through the GetManifestResourceStream method of the Assembly class. The resource name is case-sensitive and the full name is. For example:
// Get this type's assembly Assembly asm =().Assembly; // Get the stream that holds the resource // from the "" resource // NOTE1: Make sure not to close this stream, // or the Bitmap object will lose access to it // NOTE2: Also be very careful to match the case // on the resource name itself Stream stream = (""); // Load the bitmap from the stream =new Bitmap(stream);
(4) Mainfest Resource Namespaces
If passed to the GetMainfestResourcesStream method an object, it will use this type of namespace as part of the prefix for the embedded resource, such as:
// Load the stream for resource "" Stream stream = ((), "");
The Bitmap class can also directly load embedded resources, such as:
// Load image from "" =new Bitmap((), "");
2. Strongly Typed Resources
The inventory resource does not contain type information. Although the file has an extension, Bitmap classes like this determine the type based on the data itself.
(1) Application Resources(.resx) Files
The main function of the resource file (.resx) is to record the corresponding type information of the resource, because the .NET-specific XML scheme (ResX) is used to save the resource type information. An empty .resx file also has 42 lines of content, most of which are scheme information. This scheme allows for many entry information, each containing name, value, comment, type, and Multipurpose Internet Mail Extensions(MIME) type. Although this file is text-based, if you want to edit or read, it is best to do it through the resource editor of VS2005.
Name/value pairs in the .resx format are packaged in XML code that describe string or object values. When a string is added to a .resx file, the name of the string is embedded in the <data> tag and the value is included in the <value> tag, as shown in the following example.
When an object is inserted into a .resx file, the same <data> and <value> tags are used to describe the item, but the <data> tag should include a type or MIME type specifier. The type specifier retains the data type of the saved object. If the object consists of binary data, the MIME type specifier maintains the base type of stored binary information (Base64).
(2) Managing Resources
The resource editor supports six types of resources:
a. String: Displays strings in the settings grid with the Name, Value, and Comments columns of the string resource.
b. Image: Displays all image files (including .bmp, .jpg, and .gif formats). These files are exposed as Bitmap at runtime. This category also includes Windows metafiles exposed as Metafiles.
c. Icon
d. Audio: Displays sound files (including .wav, .wma, and .mp3 files). These files are exposed as byte arrays.
e. File: Displays any files that do not fit the above categories. The items in this view are text files exposed as String, or binary files exposed as byte arrays.
f. Other : Displays the settings grid used to add other types that support string serialization (for example, Font, Enum, Color, and Point). This grid contains the following columns: Name, Type, Value, and Comment.
Add resources:
You can add resources through drag and drop, menu selection, and all resource files added to the .resx file through the resource editor will be placed in the Resources folder under the project folder, and will be created if it does not exist. If a resource that already exists in the project is added to the .resx file, the resource will not be moved or copied to the Resources folder, because the resource editor manages the resource file through references to the file, and the resx file only stores the type information of the actual inventory resource.
Delete resources:
Resx can only be removed or cut from .resx through the resource editor, but not actually deleted, because you are just operating on the resource's metadata, not a real resource file (except strings, which can only be embedded). If you delete the resource file from the project, but the corresponding metadata in .resx is still there, a compilation exception will occur during compilation.
Editing resources: You can directly open the corresponding editing program through the resource editor;
(3) Resource Persistance
Linked resources are stored in the project as files; during compilation, resource data is taken from these files and placed in the application's inventory. The application's resource file (.resx) stores only relative paths or links to files on disk. For embedded resources, resource data is stored directly in a .resx file as a textual representation of binary data. In either case, the resource data will be compiled into the executable file.
Note: String resources are always embedded resources and cannot be changed; file resources are always linked resources and cannot be changed.
How to choose between embedded resources and linked resources?
-----------------------------------------------------------------
In most cases, the default link resources should be adhered to. However, it would be better to choose an embedded resource in some cases.
Embed resources:
If you need to share application resources (.resx) files between multiple projects, embedded resources are the best choice. For example, if you have a common resource file that contains company logos, trademark information, and similar content, you should use the embedded resource so that you simply copy the .resx file instead of copying the associated resource data file. Embed resources cannot be edited directly. If you try to edit an embedded resource, you will receive a message prompting you to convert the item to a linked resource for editing; this conversion is optional, but it is recommended to convert it. They must be exported and modified in an external program and then imported back to the project.
Linked resources:
As far as ease of use is concerned, the linked resources (the default value) is the best choice. Resources can be edited directly within the project and resources can be easily added or removed as needed.
-----------------------------------------------------------------
It can be determined by specifying the Persistance property of the resource. If you change the attribute to embed, deleting the resource file will not have any effect. If you change it back to the link method, the resource file will be recreated in the Resources directory.
If you manage the resource under the resource editor, you will find the BuildAction of the resource, that is, the generation operation will become "none". In fact, the Persistance property only works during the design period, and the final resource data will be compiled into the executable file.
(4) Using Typed Resources
* Use .resx files directly
Use the ResXResourceReader class to access the .resx file;
This class can enumerate XML resources (.resx) files and streams, and read sequential resource name and value pairs, which exist in the namespace. If you want to extract a specific entry, you need to do a traversal search first.
using( ResXResourceReader reader = new ResXResourceReader(@"C:\") ) { foreach( DictionaryEntry entry in reader ) { string s =("{0} ({1})= '{2}'", , (), ); (s); } }
* Use compiled .resx resources
There are three different ways you can create resource files. If your resource will contain only string data, the easiest way is to create a text file manually. If your resource will contain an object or a combination of strings with objects, you must create a .resx file or a .resources file. Only .resources files should be embedded in common language runtime assembly and affiliate assembly. Resource File Generator () converts text (.txt) files and XML-based resource (.resx) files into .resources files,
Resource generator:
Convert the .txt file to a .resources file by wrapping the method implemented by the ResourceWriter class. Also wraps ResourceReader, which allows you to use the tool to convert .resources files back to .txt files.
After compiling the project, the .resx data will be embedded as nested resources and placed in the resource inventory. For example, the default namespace of the project is A and the rest file is, then the nested resource container is , which can be viewed in ildasm. Reading to it uses the ResourceReader class and does not support random access.
using( ResourceReader reader = new ResourceReader("") ) { foreach( DictionaryEntry entry in reader ) { string s =("{0} ({1})= '{2}'", , (), ); (s); } }
In fact, you can also directly operate the .resources file through access to the inventory resource flow.
Assembly asm = (); // Load embedded .resources file using( Stream stream = ( (), "") ) { // Find resource in .resources stream using( ResourceReader reader =new ResourceReader(stream) ) { foreach( DictionaryEntry entry in reader ) { if( () =="MyString" ) { // Display string resource value ("MyString = "+ (string)); break; } } } }
All of the above require multiple steps and do not support random access, but .NET provides the ResourceManager class to support random access to resources.
(5) Resource Manager
The ResourceManager class can find regional-specific resources, provide substitute resources when the localized resource does not exist, and supports resource serialization. It is actually the encapsulation of ResourceReader. It is initialized by an embedded .resource file:
Assembly asm =().Assembly; ResourceManager resman =new ResourceManager("", asm);
Through the ResourceManager method, the caller can use the GetObject and GetString methods to access resources of a specific culture.
// Load from ResourceManager resman =new ResourceManager(()); // Access the MyString string resource from the ResourceManager // (these two techniques are equivalent for strings) string s1 = (string)("MyString"); string s2 = ("MyString");
(6) Strongly typed resource categories
Resource Manager provides a weak-type method GetObject for resources to return resources, which requires type conversion. But VS2005 and a custom tool ResXFileCodeGenerator provide solutions to this problem. When a .resx file is saved, VS2005 will apply a custom tool to generate a corresponding . file. This file provides a class with the same name as the .resx file, and the namespace in which this class is located is .
namespace ResourcesSample { ///<summary> /// A strongly typed resource class, for looking up localized /// strings, etc. ///</summary> // This class was autogenerated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .resx file and then rerun ResGen // with the /str option, or rebuild your VS project. internalclass MyResources { static global:: resourceMan; static global:: resourceCulture; internal MyResources() {} ///<summary> /// Returns the cached ResourceManager instance used by this /// class. ///</summary> internalstatic global:: ResourceManager { get { if( (resourceMan ==null) ) { global:: temp = new global::( "", typeof(MyResources).Assembly); resourceMan = temp; } return resourceMan; } } ///<summary> /// Overrides the current thread's CurrentUICulture property for /// all resource lookups using this strongly typed resource class. ///</summary> internalstatic global:: Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
From the above, we can see two characteristics of the MyResource type:
a. It provides static access to the ResourceManager through a property of type ResourceManager, so there is no need to write the previous creation logic; b. It provides static access to localized information through a property of a Culture.
Each resource provided is a strongly typed static read-only property. In an internal implementation, each property is generated by the designer's resource class generated by the managed ResourceManager object;
// Access strongly typed resources from string myString = ; Icon myIcon = ;
(7) Designer Resources
VS2005 provides resource management for the entire project. Since the file is managed from the project's property page, VS2005 stores it in the project's Properties folder. When adding .resx files in your project, the ResXFileCodeGenerator tool will automatically generate:
namespace {
...
internal class Resources {
...
You can access the resources as follows:();
The project will automatically generate a .resx file associated with the form, saving resource information such as BackgroundImage and Icon. The properties window opens the Select Resource Editor, allowing the selection of appropriate image resources. It provides two ways to import and save resources: as local resources; as project resource files. For forms, local resources are embedded in the .resx file automatically created by the form designer and associated with the form. If you select local resources, you can directly import the image into the form's resource file.
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.