.NET中使用內嵌資源

來源:互聯網
上載者:User

http://www.cnblogs.com/mmbo/archive/2010/02/05/1664454.html

Dotnet中嵌入資源(位元影像、表徵圖或游標等)有兩種方式,一是直接把資源檔加入到項目,作為嵌入資源,在代碼中通過Assembly的GetManifestResourceStream方法擷取資源的Stream。另一種方法是在項目中加入. resx資源檔,在資源檔中添加資源,由ResourceManager類統一管理其中的資源。

下面分別詳述這兩種方法

一、  使用GetManifestResourceStream讀取嵌入資源1、 加入資源檔

直接把要嵌入到程式集的資源檔加入到項目中,可以加在項目的根目錄,可以加在項目的任何目錄中。

2、 設定資源檔的“BuildAction”屬性

將嵌入資源檔的“BuildAction”屬性設定為“Embedded Resource”

3、 代碼中使用嵌入資源

 //獲得正在運行類所在的名稱空間

Type type = MethodBase.GetCurrentMethod().DeclaringType;

string _namespace
= type.Namespace;

//擷取當前主程式集

Assembly currentAssembly = Assembly.GetExecutingAssembly();

//資源的根名稱

string resourceRootName
= _namespace
+ ".ResourceTest";

//執行個體化資源管理類

ResourceManager resourceManager =
new ResourceManager(resourceRootName, currentAssembly);

//根據資源名獲得資來源物件

Icon myIcon = (Icon)resourceManager.GetObject("IconTest");

 

 

2:

//獲得正在運行類所在的名稱空間

Type type = MethodBase.GetCurrentMethod().DeclaringType;

string _namespace
= type.Namespace;

//獲得當前啟動並執行Assembly

Assembly _assembly = Assembly.GetExecutingAssembly();

//根據名稱空間和檔案名稱產生資源名稱

string resourceName
= _namespace
+ ".directory.BitmapManifest.bmp";

//根據資源名稱從Assembly中擷取此資源的Stream

Stream stream = _assembly.GetManifestResourceStream(resourceName);

Image myImage = Image.FromStream(stream);

 

 

3:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.