|
C#最常使用的相對(duì)路徑是從當(dāng)前程序所在路徑開(kāi)始相對(duì)尋徑,找到要找的路徑,即以下兩種最簡(jiǎn)單的方式:
1. 程序根目錄.(即exe程序所在路徑)//下面兩個(gè)路徑是等價(jià)的,都是exe程序所在路徑(通常是bin\Debug\下)的Data文件夾下的test文本文件string Path1 = @'.\Data\test.txt'; string Path2 = @'Data\test.txt';
2. 上級(jí)目錄..string Path3 = @'..\Data\test.txt'; //程序根目錄的上級(jí)目錄(通常是bin\下)的Data文件夾下的test文本文件string Path4 = @'..\..\Data\test.txt'; //程序根目錄的上兩級(jí)目錄(通常是程序名\下)的Data文件夾下的test文本文件
當(dāng)然,C#還可以靠指定的方式獲得相對(duì)路徑。應(yīng)用VS2010創(chuàng)建了一WinForm項(xiàng)目,項(xiàng)目名為RelativePath,放在桌面上。編寫(xiě)代碼通過(guò)八種特定方式獲取相對(duì)路徑并輸出顯示,運(yùn)行效果如下:
下面簡(jiǎn)要的介紹一下這八種獲得相對(duì)路徑的方式:
1. 獲取和設(shè)置當(dāng)前目錄(該進(jìn)程從中啟動(dòng)的目錄)的完全限定路徑string str1 = System.Environment.CurrentDirectory; //Result: C:xxxxxx
2. 獲取應(yīng)用程序的當(dāng)前工作目錄string str2 = System.IO.Directory.GetCurrentDirectory(); //Result: C:xxxxxx
這個(gè)不一定是程序從中啟動(dòng)的目錄啊,有可能程序放在C:\xxx里,這個(gè)函數(shù)有可能返回C:\Documents and Settings\WSY\,或者C:\Program Files\Adobe\,有時(shí)不一定返回什么東西,這是程序最后一次操作過(guò)的目錄,比如你用Word打開(kāi)了E:\doc\my.doc這個(gè)文件,此時(shí)執(zhí)行這個(gè)方法就返回了E:\doc了。
3. 獲取啟動(dòng)了應(yīng)用程序的可執(zhí)行文件的路徑,不包括可執(zhí)行文件的名稱(chēng)string str3 = System.Windows.Forms.Application.StartupPath; //Result: C:xxxxxx
4. 獲取啟動(dòng)了應(yīng)用程序的可執(zhí)行文件的路徑,包括可執(zhí)行文件的名稱(chēng)string str4 = System.Windows.Forms.Application.ExecutablePath; //Result: C:xxxxxxxxx.EXE
5. 獲取當(dāng)前 Thread 的當(dāng)前應(yīng)用程序域的基目錄,它由程序集沖突解決程序用來(lái)探測(cè)程序集string str5 = System.AppDomain.CurrentDomain.BaseDirectory; //Result: C:xxxxxx
6. 獲取和設(shè)置包含該應(yīng)用程序的目錄的名稱(chēng)string str6 = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase; //Result: C:xxxxxx
7. 獲取當(dāng)前進(jìn)程的完整路徑,包含文件名string str7 = this.GetType().Assembly.Location; //Result: C:xxxxxxxxx.exe
8. 獲取新的 Process 組件并將其與當(dāng)前活動(dòng)的進(jìn)程關(guān)聯(lián)的主模塊的完整路徑,包含文件名string str8 = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName; //Result: C:xxxxxxxxx.vshost.exe
此外,更多見(jiàn)的通過(guò)XML文件配置具體的路徑來(lái)達(dá)到合理的規(guī)劃配置文件的具體存放位置,如WEB中的配置文件中的路徑 string path = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @'moduleM3ExampleMuColor.txt';StreamReader smRead = new StreamReader(path, System.Text.Encoding.Default); //設(shè)置路徑 |
|
|
來(lái)自: 李珂consilpa3m > 《待分類(lèi)》