一旦通過枚舉清單資源或硬編碼一個您想要的清單資源而知道了清單資源的名稱,就可以通過 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);
}
文章來源于領測軟件測試網 http://www.kjueaiud.com/