有时候不希望资源暴露给用户,需要将一些资源写入到程序体中(例如图片等),这时候就需要使用内嵌资源了,使用内嵌资源的方法如下:
可以使用 ResourceManager 类在运行时检索“嵌入的资源”(即已经编译到应用程序或类库中的资源)。ResourceManager 类的每个实例都与一个程序集关联并且管理对嵌入到该程序集中的资源的检索。
检索资源
- 创建一个程序集引用,引用包含要访问的资源的程序集。如果尚未加载包含资源的程序集,则必须在此时加载它。
- 创建 ResourceManager 类的实例以检索资源。
- 指定嵌入文件的基名称并提供对包含资源的程序集的引用。
注意 嵌入的资源文件的基名称是嵌入了资源文件的命名空间的名称加上不带任何扩展名的文件名。例如,myApplication 命名空间中名为 Resource1.resX 的文件的基名称是 myApplication.Resource1。命名空间可在 *.Designer.cs中查看。
- 调用 ResourceManager.GetString 方法或 ResourceManager.GetObject 方法以检索资源。
- 若要检索“字符串”资源,请调用 GetString 方法。
- 若要检索其他类型的资源,请调用 GetObject 方法。通过 GetObject 方法检索到的资源必须显式转换成对应的类型。
// C# // Gets a reference to the same assembly that // contains the type that is creating the ResourceManager. System.Reflection.Assembly myAssembly; MyAssembly = this.GetType().Assembly; // Gets a reference to a different assembly. System.Reflection.Assembly myOtherAssembly; myOtherAssembly = System.Reflection.Assembly.Load("ResourceAssembly"); // Creates the ResourceManager. System.Resources.ResourceManager myManager = new System.Resources.ResourceManager("ResourceNamespace.myResources", myAssembly); // Retrieves String and Image resources. System.String myString; System.Drawing.Image myImage; myString = myManager.GetString("StringResource"); myImage = (System.Drawing.Image)myManager.GetObject("ImageResource");