如果(大多数情况下)您使用 Visual Studio?NET 来开发和构建程序集,则用命令行嵌入清单资源的方法不可能非常吸引您。这种情况下,您可以将资源添加到 Windows 窗体项目中,该方法将把合适的命令行参数传递给编译器。
要将资源添加到项目中,请在 Solution Explorer 中右键单击项目,然后选择 Add New Item,并选择您想作为资源嵌入的文件。文件将复制到项目的目录中,但仍然不会被嵌入。要使文件作为资源嵌入,请右键单击文件,并选择 Properties,然后将 Build Action 从 Content(默认)更改为 Embedded Resource(嵌入资源)
这种嵌入资源的方法会使 Visual Studio .NET 为您创建一个备用资源名,其组成类似这样:
<defaultNamespace>.<folderName>.<fileName>
资源名称的默认命名空间部分是项目本身的默认命名空间,
它是通过
Solution Explorer->Properties->Common Properties->General->Default Namespace 来设置的。
由于这是在生成新类时,新类得到的相同命名空间,所以这就使通过使用类型和部分资源名称来加载资源变得很方便。
如果文件碰巧位于项目的子文件夹中,就需要在文件夹名称中包括子文件夹,并用点替换反斜杠。
例如,一个名为 Azul.jpg 的位图位于项目根下面的 foo/bar 文件夹中,要加载它就需要这样做:
// If this code called within the ResourcesApp.Form1 class, // and the file is /foo/bar/Azul.jpg, // will load ResourcesApp.foo.bar.Azul.jpg this.BackgroundImage = new Bitmap(this.GetType(), "foo.bar.Azul.jpg");那么如何从程序集中加载指定的清单资源呢?我们可以用Assembly.GetManifestResourceStream(String) 。
其中参数为资源名称,即上面<defaultNamespace>.<folderName>.<fileName>namespace JJSoft.FrameWorks.PayPal.SDK.Resources { ////// Summary description for ResourceHelper. /// public class ResourceHelper { ////// Reads an embedded resource within the assembly. /// /// The path to the resource without the Constants.RESOURCE_ROOT prepended /// A stream to the resource public static Stream GetResourceStream(string name) { return Assembly.GetExecutingAssembly().GetManifestResourceStream(Constants.RESOURCE_ROOT + name); } } }其中Assembly.GetExecutingAssembly()获取包含当前执行的代码的程序集。若要获取包含调用当前所执行代码的方法的程序集,请使用 GetCallingAssembly