Home>

1. resource basics

(1) manifest resources

Resources are added to the assembly during compilation.If you are embedding resources into an assembly,You must add the file to the project,The files are automatically copied to the resources folder of the project folder.If i want to embed it in an assembly,You also need to select the file,Modify its property "build action" to "embedded resource" and default to "content".

Once set as an embedded resource,Then it becomes part of the assembly in the resource manifest.Per assembly,Whether static or dynamic,Each contains a collection of data describing how the elements in the assembly relate to each other.The assembly manifest contains these assembly metadata.The assembly manifest contains all the metadata needed to specify the version requirements and security identification of the assembly,And all the metadata needed to define the scope of the assembly and resolve references to resources and classes.

(2) naming mainfest resources

To view a file that has been properly embedded in the project output assembly,You can use the sdk tool ildasm.exe, which is actually the msil disassembler,It can display all embedded resources in the mainfest view of your assembly.

It is displayed as an .mresource entry in ildasm, and the resource name display format is as follows:

defaultnamespace.foldername.filename

The defaultnamespace can be changed in the Applications tab of the project's properties page.

(3) loading mainfest resources

Also programmatically enumerate the list,You need to use the getmainifestresourcenames method of the system.reflection.assembly class. You can also retrieve specific types of assemblies,For example, the assembly class also provides getassembly, getcallingassembly, getentryassembly, and getexecutingassembly.

//get this type "s assembly
assembly asm=this.gettype (). assembly;
//enumerate the assembly "s manifest resources
foreach (string resourcename in asm.getmanifestresourcenames ()) {
messagebox.show (resourcename);
}

type is the root of the system.reflection function,It 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 class events,And the modules and assemblies in which the class is deployed.

Indicates that a type is the only type object;that is, two type objects refer to if and only if they represent the same type,Before referencing the same object.This allows comparison of type objects using reference equations. The type class represents a type declaration:class type, interface type, array type, value type, enumeration type, type parameter, generic type definition,And generic types of open or closed construction.The object.gettype method returns a type object representing the type of the instance.

If you know the name of the resource,You can load the specified manifest resource through the getmanifestresourcestream method of the assembly class.Resource names are case sensitive,And it's the full name.E.g:

//get this type "s assembly
assembly asm=this.gettype (). assembly;
//get the stream that holds the resource
//from the "resourcessample.azul.jpg" 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 =
asm.getmanifestresourcestream ("resourcessample.azul.jpg");
//load the bitmap from the stream
this.backgroundimage=new bitmap (stream);

(4) mainfest resource namespaces

If passed to the getmainfestresourcesstream method a system.type object, it uses this type of namespace as part of the prefix of the embedded resource,Such as:

//load the stream for resource "resourcessample.azul.jpg"
stream stream=asm.getmanifestresourcestream (this.gettype (), "azul.jpg");

The bitmap class can also directly load embedded resources,Such as:

//load image from "resourcesapp.azul.jpg"
this.backgroundimage=new bitmap (this.gettype (), "azul.jpg");

2. strongly typed resources

Type information is not included in the manifest resource,Although the file has an extension,But similar bitmap classes are based on the data itself to determine the type.

(1) application resources (.resx) files

The main role of a resource file (.resx) is to record the corresponding type information of the resource.Since adopted.net specific xml scheme (resx) to save resource type information.An empty .resx file also has 42 lines of content, most of which are scheme information.This scheme allows a lot of entry information,Each contains name, value, comment, type, and multipurpose internet mail extensions (mime) type. Although this file is text-based,But if i want to edit or read,It is best done through the resource editor of vs2005.

Name/value pairs in .resx format are packaged in xml code,It describes a string or object value.When a string is added to a .resx file,The name of the string is embedded in thetag, and the value is included in thetag, as shown in the following example.

When an object is inserted into a .resx file,Use the same<data>and<value>tags to describe the item,But thetag 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 holds the base type (base64) of the stored binary information.

(2) managing resources

The resource editor supports six types of resources:

a. String:Displays the string in the settings grid with the Name, Value, and Comment columns of the string resource.

b. Image:Display all image files (including .bmp, .jpg, and .gif formats). These files are exposed as a bitmap at runtime. This category also includes windows metafiles exposed as metafiles.

c. icon

d. Audio:Display sound files (including .wav, .wma, and .mp3 files). These files are exposed as byte arrays.

e. Files:Shows any files that are not suitable for the above categories.The items in this view are text files exposed as string,Or a binary file exposed as a byte array.

f. Other:Displays a settings grid for adding 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 by drag and drop, menu selection,Added to through the resource editor.All resource files of the resx file will be placed in the resources folder under the project folder,Created if it does not exist.If you add a resource that already exists in the project.resx file, this resource will not be moved or copied to the resources folder,Because the resource editor manages resource files through references to files,The resx file only stores the type information of the actual inventory resource.

Delete resource:

From the resource editor only.remove or cut resources in resx,Without actually deleting it,Because you are only manipulating the metadata of the resource,Rather than a real resource file (except for strings,It can only be embedded). If you delete a resource file from a project,But the corresponding metadata in .resx is still there,This will cause a compilation exception during compilation.

Editing resources:You can directly open the corresponding editing program through the resource editor;

(3) resource persistance

Linked resources are stored as files in the project;During compilation,Get resource data from these files,And put it in the manifest of the application.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 the .resx file as a textual representation of the binary data. In either case,The resource data is compiled into an executable file.

Note:String resources are always embedded resources,Cannot be changedFile resources are always linked resources,It cannot be changed.

How do I choose between embedded and linked resources?---------------------------------------------- -------------------

In most circumstances,Should stick to the default link resource.However, in some cases it may be better to choose embedded resources.

Embedded resources:If you need to share application resource (.resx) files between multiple projects, embedded resources are the best choice.For example, if you have a universal resource file containing company logos, trademark information, and the like,You should use embedded resources,This way you only need to copy the .resx file instead of the associated resource data file.You cannot edit embedded resources directly.If you try to edit an embedded resource,You will receive a message,Prompts you to convert the item to a linked resource for editing;This conversion is optional,But conversion is recommended.They must be exported and modified in external programs,Then import it back into the project.

Linked resources:In terms of ease of use,Linked resources (the default) are the best choice.You can edit resources directly within the project,And you can easily add or remove resources as needed.

-------------------------------------------------- ---------------

Can be determined by specifying the persistence property of the resource.If you change the property to embed,Deleting the resource file will have no effect.If you change back to the link mode at this time,This resource file will be re-created in the resources directory.

If you manage resources under the resource editor,You will find the buildaction of the resource, that is, the build operation will become "None". Actually the persistence property only works during design time,The final resource data is compiled into an executable file.

(4) using typed resources

* Use directly.resx file

Use the resxresourcereader class to access it.resx file

This class can enumerate xml resource (.resx) files and streams,And read sequential resource name and value pairs,Exists in the namespace system.resources. If i want to extract a specific entry,You need to traverse the search first.

using (resxresourcereader reader =
 new resxresourcereader (@ "c:\ myresources.resx")) {
 foreach (dictionaryentry entry in reader) {
  string s=string.format ("{0} ({1}) =" {2} "",    entry.key, entry.value.gettype (), entry.value);
   messagebox.show (s);
  }
}

* Use compiled.resx resources

You can create resource files in three different ways.If your resource will only contain string data,The easiest way is to create the text file manually.If your resource will contain objects or a combination of strings and objects,You must create a .resx file or a .resources file. Only .resources files should be embedded in the common language runtime assembly and satellite assemblies.Resource file generator (resgen.exe) converts text (.txt) files and xml-based resources (.resx) files into .resources files

Resource generator resgen.exe:

Converts a .txt file to a .resources file by wrapping a method implemented by the resourcewriter class.resgen.exe also wraps resourcereader, which allows you to use the tool to convert .resources files back to .txt files.

After compiling the project.Resx data is embedded as a nested resource in the resource list,For example, the default namespace of the project is a and the rest file is b.resx. The nested resource container is a.b.resources, which can be viewed in ildasm. It uses the resourcereader class for reading and does not support random access.

using (resourcereader reader =
 new resourcereader ("myresources.resources")) {
 foreach (dictionaryentry entry in reader) {
  string s=string.format ("{0} ({1}) =" {2} "",    entry.key, entry.value.gettype (), entry.value);
   messagebox.show (s);
  }
}

In fact, .resources files can also be manipulated directly by accessing the inventory resource stream.

assembly asm=assembly.getexecutingassembly ();
//load embedded .resources file
using (
  stream stream=asm.getmanifestresourcestream (
  this.gettype (),  "myresources.resources")) {
 //find resource in .resources stream
 using (resourcereader reader=new resourcereader (stream)) {
  foreach (dictionaryentry entry in reader) {
   if (entry.key.tostring () == "mystring") {
    //display string resource value
     messagebox.show ("mystring =" + (string) entry.value);
    break;
    }
   }
  }
}

All of the above require multiple steps and do not support random access.However, .net provides the resourcemanager class to support random access to resources.

(5) resource manager

The resourcemanager class finds culture-specific resources,Provide alternative resources when localized resources do not exist,And supports resource serialization,It is actually a wrapper for resourcereader. It consists of an embed.Resource file initialization:

assembly asm=this.gettype (). assembly;
resourcemanager resman=new resourcemanager ("resourcessample.myresources", asm);

Resourcemanager's methods allow callers to use two methods, getobject and getstring, to access resources in a specific culture.

//load resourcessample.mainform.resources from mainform.resx
resourcemanager resman=new resourcemanager (this.gettype ());
//access the mystring string resource from the resourcemanager
//(these two techniques are equivalent for strings)
string s1=(string) resman.getobject ("mystring");
string s2=resman.getstring ("mystring");

(6) Strongly typed resource class

The resource manager provides a weakly typed getObject method for resources to return resources.Requires type conversion.But vs2005 and a custom tool resxfilecodegenerator provide a solution to this problem.When a .resx file is saved,vs2005 will apply a custom tool to generate a corresponding .designer.cs file. This file provides a class with the same name as the .resx file.The namespace of this class is defaultnamespace.projectpath.

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 ::system.resources.resourcemanager resourceman;
   static global ::system.globalization.cultureinfo resourceculture;
   internal myresources () {}
   ///<summary>
   ///returns the cached resourcemanager instance used by this
   ///class.
   ///</summary>
   internalstatic global ::
    system.resources.resourcemanager resourcemanager {
    get {
     if ((resourceman == null)) {
      global ::system.resources.resourcemanager temp =
       new global ::system.resources.resourcemanager (
        "resourcessample.myresources",        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 ::system.globalization.cultureinfo culture {
    get {return resourceculture;}
    set {resourceculture=value;}
   }
  }
}

From the above, two characteristics of the myresource type can be seen:

a. It provides static access to the resourcemanager through a property of type resourcemanager,There is no need to write the previous creation logic; b. The cultureinfo object provides static access to localized information through a culture attribute;

Each resource provided is a strongly typed static read-only property.In the internal implementation,Each attribute is generated by the resource class generated by the designer using a managed resourcemananger object;

//access strongly typed resources from myresources.resx
string mystring=myresources.mystring;
icon myicon=myresources.myicon;

(7) designer resources

vs2005 provides resource management for the entire project.Since the resources.resx file is managed from the project's property page,So vs2005 will store it in the project's properties folder.When adding in the project.When resx file, resxfilecodegenerator tool will automatically generate resources.designer.cs:

namespace resourcessample.properties {

...

internal class resources {

...

You can access resources as follows:messagebox.show (properties.resources.mystring);

The project will automatically generate a form associated with the form.resx file, which holds resource information like backgroundimage and icon.The properties window can open the selection resource editor,Allows selection of appropriate image resources.It provides two ways to import and save resources:as local resources;As a project resource file.For forms,Local resources are embedded into the form designer and are created automatically.resx file and associated with the form,If you choose local resources,You can directly import the picture into the resource file of the form.

c
  • Previous ASP definition array method skills
  • Next SQL Server database table records only retain N days of graphic tutorials