1. 程式人生 > 其它 >C#獲取當前程式執行路徑的幾種方法

C#獲取當前程式執行路徑的幾種方法

     1.//獲取模組的完整路徑。

             string path1 = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;

             2.//獲取和設定當前目錄(該程序從中啟動的目錄)的完全限定目錄

             string path2 = System.Environment.CurrentDirectory;

             3.//獲取應用程式的當前工作目錄

             string path3 = System.IO.Directory.GetCurrentDirectory();

             4.//獲取程式的基目錄

             string path4 = System.AppDomain.CurrentDomain.BaseDirectory;

             5.//獲取和設定包括該應用程式的目錄的名稱

             string path5 = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;

             6.//獲取啟動了應用程式的可執行檔案的路徑

             string path6 = System.Windows.Forms.Application.StartupPath;

             7.//獲取啟動了應用程式的可執行檔案的路徑及檔名

             string path7 = System.Windows.Forms.Application.ExecutablePath;

             StringBuilder str = new StringBuilder();//拼接字串輸出

             str.Append("System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName:" + path1);

             str.Append("System.Environment.CurrentDirectory:" + path2);

             str.Append("System.IO.Directory.GetCurrentDirectory():" + path3);

             str.Append("System.AppDomain.CurrentDomain.BaseDirectory:" + path4);

             str.Append("System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase:" + path5);

             str.Append("System.Windows.Forms.Application.StartupPath:" + path6);

             str.Append("System.Windows.Forms.Application.ExecutablePath:" + path7);

             string allPath = str.ToString();
             輸出執行結果:

1.System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName:

C:\Users\Lenovo\Desktop\QRCode\QRCode\bin\Debug\QRCode.vshost.exe

 


2.System.Environment.CurrentDirectory:

C:\Users\Lenovo\Desktop\QRCode\QRCode\bin\Debug

 


3.System.IO.Directory.GetCurrentDirectory():

C:\Users\Lenovo\Desktop\QRCode\QRCode\bin\Debug

 


4.System.AppDomain.CurrentDomain.BaseDirectory:

C:\Users\Lenovo\Desktop\QRCode\QRCode\bin\Debug\

 


5.System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase:

C:\Users\Lenovo\Desktop\QRCode\QRCode\bin\Debug\

 


6.System.Windows.Forms.Application.StartupPath:

C:\Users\Lenovo\Desktop\QRCode\QRCode\bin\Debug

 


7.System.Windows.Forms.Application.ExecutablePath:

C:\Users\Lenovo\Desktop\QRCode\QRCode\bin\Debug\QRCode.EXE