C#獲取相對(duì)路徑的八種方法
C#獲取相對(duì)路徑1.
獲取和設(shè)置當(dāng)前目錄的完全限定路徑。
- string str = System.Environment.CurrentDirectory;
- Result: C:\xxx\xxx
C#獲取相對(duì)路徑2.
獲取啟動(dòng)了應(yīng)用程序的可執(zhí)行文件的路徑,不包括可執(zhí)行文件的名稱。
- string str = System. Windows .Forms.Application.StartupPath;
- Result: C:\xxx\xxx
C#獲取相對(duì)路徑3.
獲取新的 Process 組件并將其與當(dāng)前活動(dòng)的進(jìn)程關(guān)聯(lián)的主模塊的完整路徑,包含文件名。
- string str = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
- Result: C:\xxx\xxx\xxx.exe
C#獲取相對(duì)路徑4.
獲取當(dāng)前 Thread 的當(dāng)前應(yīng)用程序域的基目錄,它由程序集沖突解決程序用來探測(cè)程序集。
- string str = System.AppDomain.CurrentDomain.BaseDirectory;
- Result: C:\xxx\xxx\
C#獲取相對(duì)路徑5.
獲取應(yīng)用程序的當(dāng)前工作目錄。
- string str = System.IO.Directory.GetCurrentDirectory();
- Result: C:\xxx\xxx
C#獲取相對(duì)路徑6.
獲取和設(shè)置包含該應(yīng)用程序的目錄的名稱。
- string str = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
- Result: C:\xxx\xxx\
C#獲取相對(duì)路徑7.
獲取當(dāng)前進(jìn)程的完整路徑,包含文件名。
- string str = this.GetType().Assembly.Location;
- Result: C:\xxx\xxx\xxx.exe
C#獲取相對(duì)路徑8.
獲取啟動(dòng)了應(yīng)用程序的可執(zhí)行文件的路徑,包括可執(zhí)行文件的名稱。
- string str = System. Windows .Forms.Application.ExecutablePath;
- Result: C:\xxx\xxx\xxx.exe
此外,更多見的通過XML文件配置具體的路徑來達(dá)到合理的規(guī)劃配置文件的具體存放位置,如WEB中的配置文件中的路徑。
【編輯推薦】