方法1 GetManifestResourceStream
VB.NET中資源的名稱為:項目默認命名空間.資源文件名
C#中則是:項目命名空間.資源文件所在文件夾名.資源文件名
例如:
istr = assm.GetManifestResourceStream("項目命名空間.資源文件所在文件夾名.資源文件名");
讀取資源文件
注意: 資源文件一定要是 嵌入的資源; 並且資源文件名要帶擴展名的
Assembly assm = Assembly.GetExecutingAssembly(); Stream istr = assm.GetManifestResourceStream("CreateDatabase.Resources.aa.txt"); System.IO.StreamReader sr = new System.IO.StreamReader(istr); string str = sr.ReadLine();
方法2 ResourceManager.GetObject("文件名")
讀取資源文件
Assembly myAssem = Assembly.GetEntryAssembly(); ResourceManager rm = new ResourceManager("CreateDatabase.Properties.Resources", myAssem); //CreateDatabase是你程序的命名空間,CreateDatabase.Properties 是資源類Resources的命名空間 // this.pictureBox1.Image = (Image)rm.GetObject("aa"); string str = rm.GetString("aa"); //資源文件名稱不帶擴展名
CreateDatabase.Properties 是資源類Resources的命名空間 , 資源文件名稱不帶擴展名
二、C#嵌入dll到資源釋放的問題
轉載自:
點擊打開鏈接
有些程序運行的時候,可能調用外部的dll,用戶使用時可能會不小心丟失這些dll,導致程序無法正常運行,因此可以考慮將這些dll嵌入到資源中,啟動時自動釋放。對於托管的dll,我們可以用打包軟件合成一個exe(例如利用Imerge),但是對於一些用C++等寫的非托管dll,就比較麻煩。在這種情況下,大家可以考慮本文介紹的方法。
1、將需要用到的dll文件嵌入資源文件中。
(1)將需要用到的dll文件拷貝到工程中;


(2)修改“生成操作”為“嵌入的資源”;
這樣就完成了dll文件嵌入資源的過程。
2、編寫自動釋放的過程 (保存資源文件到本地)
(1)
void ReleaseDLL() { byte[] byDll = global::命名空間.Properties.Resources.test;//獲取嵌入dll文件的字節數組 string strPath = Application.StartupPath + @"\test.dll";//設置釋放路徑 導出路徑 //創建dll文件(覆蓋模式) using (FileStream fs = new FileStream(strPath, FileMode.Create)) { fs.Write(byDll, 0, byDll.Length); } }
(注意:一定要設置 嵌入的資源)
在程序啟動時,首先調用上面的函數完成dll文件的釋放,然后程序就能夠正常運行了。這種做法只是筆者在實際項目中有時采用的一種方式,相信對大家也有一定的參考價值。
(2)、 我使用這種方式也可以導出,但是導出的文件大小不對,文件損壞了,使用不了
System.Resources.ResourceManager rm = Properties.Resources.ResourceManager; System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bin = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); using (FileStream Stream = new FileStream("導出目錄" + "\\test.dll", FileMode.Create))
{
bin.Serialize(Stream, rm.GetObject("test")); //test.dll名稱
}