c# winfrom資源文件的調用和路徑全解


  • 一>獲取非嵌入程序集資源文件路徑和方法(C#中獲取程序當前路徑的集中方法)

System.Diagnostics命名空間 :

string str1 =Process.GetCurrentProcess().MainModule.FileName;//可獲得當前執行的exe的文件名。 

System 命名空間:

string str2=Environment.CurrentDirectory;//獲取和設置當前目錄(即該進程從中啟動的目錄)的完全限定路徑。

System.IO命名空間:

string str3=Directory.GetCurrentDirectory();//獲取應用程序的當前工作目錄。

string str4=AppDomain.CurrentDomain.BaseDirectory;//獲取基目錄,它由程序集沖突解決程序用來探測程序集。

string str5=Application.StartupPath;//獲取啟動了應用程序的可執行文件的路徑,不包括可執行文件的名稱。

string str6=Application.ExecutablePath;//獲取啟動了應用程序的可執行文件的路徑,包括可執行文件的名稱。

string str7=AppDomain.CurrentDomain.SetupInformation.ApplicationBase;//獲取或設置包含該應用程序的目錄的名稱。

其他方法介紹:

1. System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName 獲取模塊的完整路徑。

2. System.Environment.CurrentDirectory 獲取和設置當前目錄(該進程從中啟動的目錄)的完全限定目錄。

3. System.IO.Directory.GetCurrentDirectory()  獲取應用程序的當前工作目錄。這個不一定是程序從中啟動的目錄啊,有可能程序放在C:"www里,這個函數有可能返回C:"Documents and Settings"ZYB",或者C:"Program Files"Adobe",有時不一定返回什么東東,我也搞不懂了。

4. System.AppDomain.CurrentDomain.BaseDirectory 獲取程序的基目錄。

5. System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase 獲取和設置包括該應用程序的目錄的名稱。

6. System.Windows.Forms.Application.StartupPath  獲取啟動了應用程序的可執行文件的路徑。效果和2、5一樣。只是5返回的字符串后面多了一個"""而已

7. System.Windows.Forms.Application.ExecutablePath 獲取啟動了應用程序的可執行文件的路徑及文件名,效果和1一樣。

  • 二>獲取嵌入的資源文件的路徑和方法

eg1.獲取項目資源文件中的圖片:

//pictureBox1.BackgroundImage = global::工程名.Properties.Resources.圖片名(沒有后綴);

另附一種方法:

//獲取項目中“資源文件”的數據

Assembly asm = Assembly.GetExecutingAssembly(); 
ResourceManager rm = new ResourceManager("TestCustomForm.Properties.Resources", asm); 
String str = rm.GetString("ApplicationName");    //添加到資源文件的字符串 
Image img = rm.GetObject("bamboo") as Image;  //添加到資源文件的圖片

 eg2.獲取項目添加項文件夾下的htm文件(注意:文件屬性中生成操作得改為(嵌入的資源))不包括具體調用htm中具體字節方法:

調用方法: 

string aboutHtml = this.getStringResource("HTMLPage1.htm");

 MessageBox.Show(aboutHtml);

private string getStringResource(String name)
        {
            //根據assembly名稱加載程序集到當前的Appdomain
            //System.Reflection.Assembly ass = System.Reflection.Assembly.Load("MyAssembly");
            System.Reflection.Assembly asm = this.GetType().Assembly;
            //在這個文件中列出的所有資源
            System.Diagnostics.Debug.WriteLine("found resouces:");
            foreach (String rs in asm.GetManifestResourceNames())
                System.Diagnostics.Debug.WriteLine(rs);
            name = this.GetType().Namespace + "." + name;

            System.IO.Stream strm = asm.GetManifestResourceStream(name);
            //默認的系統編碼轉換為字符串
            return new System.IO.StreamReader(strm, System.Text.Encoding.Default).ReadToEnd();
        }

圖片調用:Image.FromStream(Assembly.GetExecutingAssembly().GetManifestResourceStream(@"TestCustomForm.Res.button.btndown.bmp"));

其中:TestCustomForm為項目名稱,Res為項目下的文件夾,button為Res的子文件夾,btndown.bmp是文件名稱。

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM