一旦通過枚舉清單資源或硬編碼一個您想要的清單資源而知道了清單資源的名稱,就可以通過 Assembly 類的 GetManifestResourceStream 方法將該清單資源作為原始字節流進行加載,如下所示:
using System.IO;public Form1() { ... // Get this type's assembly Assembly assem = this.GetType().Assembly; // Get the stream that holds the resource // NOTE1: Make sure not to close this stream! // NOTE2: Also be very careful to match the case // on the resource name itself Stream stream = assem.GetManifestResourceStream("Azul.jpg"); // Load the bitmap from the stream this.BackgroundImage = new Bitmap(stream);}
因為資源可以像類型名稱一樣有沖突,所以最好用資源自己的“命名空間”來嵌入資源,該操作可以使用 /resource 開關的擴展格式來完成:
C:\>csc myApp.cs /resource:c:\...\azul.jpg,ResourcesApp.Azul.jpg
注意在要嵌入的文件名的逗號后面使用的備用資源名稱。備用資源名稱允許您為資源任意地提供時間嵌套名稱,不管文件名是什么。它是設置在程序集中的備用名稱,如圖 2 所示。

圖 2. 使用備用名稱的嵌入資源
下面是使用備用名稱的更新后的資源加載代碼:
public Form1() { ... // Get this type's assembly Assembly assem = this.GetType().Assembly; // Load a resource with an alternate name Stream stream = assem.GetManifestResourceStream("ResourcesApp.Azul.jpg"); // Load the bitmap from the stream this.BackgroundImage = new Bitmap(stream);}
為了更方便,如果您的資源和加載資源的類碰巧使用了相同的命名空間,則可以將類的類型作為可選的第一參數傳遞給 GetManifestResourceStream:
namespace ResourcesApp { public class Form1 : Form { public Form1() { ... // Get this type's assembly Assembly assem = this.GetType().Assembly; // Load the resource using a namespace // Will load resource named "ResourcesApp.Azul.jpg" Stream stream = assem.GetManifestResourceStream(this.GetType(), "Azul.jpg"); // Load the bitmap from the stream this.BackgroundImage = new Bitmap(stream); } ... }}
文章來源于領測軟件測試網 http://www.kjueaiud.com/