C#獲取當前程序所在路徑的各種方法


一、獲取完整包含執行程序的路徑:exe文件所在的目錄+.exe文件名

1、方法1:Type.Assembly.Location

//獲取當前進程的完整路徑,包含文件名(進程名)。
string str = this.GetType().Assembly.Location;

結果:X:\xxx\xxx\xxx.exe(.exe文件所在的目錄+.exe文件名)

2、方法2:System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName

//獲取新的 Process 組件並將其與當前活動的進程關聯的主模塊的完整路徑,包含文件名(進程名)。
string str = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;

結果:X:\xxx\xxx\xxx.exe(.exe文件所在的目錄+.exe文件名)

3、方法3:System.Windows.Forms.Application.ExecutablePath

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

結果:X:\xxx\xxx\xxx.exe(.exe文件所在的目錄+.exe文件名)

 

二、獲取當前程序所在路徑:exe文件所在的目錄(不包含xxx.exe)

1、方法1:System.Environment.CurrentDirectory

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

結果:X:\xxx\xxx(.exe文件所在的目錄)

2、方法2:System.AppDomain.CurrentDomain.BaseDirectory

//獲取當前 Thread 的當前應用程序域的基目錄,它由程序集沖突解決程序用來探測程序集。
string str = System.AppDomain.CurrentDomain.BaseDirectory;

結果:X:\xxx\xxx(.exe文件所在的目錄)

3、方法3:System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase

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

結果:X:\xxx\xxx\(.exe文件所在的目錄+"\")

4、方法4:System.Windows.Forms.Application.StartupPath

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

結果:X:\xxx\xxx(.exe文件所在的目錄)

5、方法5:System.IO.Directory.GetCurrentDirectory()

//獲取應用程序的當前工作目錄(不可靠)。
string str = System.IO.Directory.GetCurrentDirectory();

結果:X:\xxx\xxx(.exe文件所在的目錄)

 

參考鏈接:C#獲取當前程序運行路徑的方法集合 - 魔法皇帝 - 博客園 (cnblogs.com)


免責聲明!

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



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