1. 程式人生 > >C#: 獲取當前路徑不要用Environment.CurrentDirectory

C#: 獲取當前路徑不要用Environment.CurrentDirectory

網上大把文章寫到C#獲取當前路徑的方法如下:

// 獲取程式的基目錄。
System.AppDomain.CurrentDomain.BaseDirectory // 獲取模組的完整路徑。 System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName // 獲取和設定當前目錄(該程序從中啟動的目錄)的完全限定目錄。 System.Environment.CurrentDirectory // 獲取應用程式的當前工作目錄。 System.IO.Directory.GetCurrentDirectory() // 獲取和設定包括該應用程式的目錄的名稱。 System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase // 獲取啟動了應用程式的可執行檔案的路徑。 System.Windows.Forms.Application.StartupPath // 獲取啟動了應用程式的可執行檔案的路徑及檔名 System.Windows.Forms.Application.ExecutablePath 

我以前寫的程式碼中獲取當前路徑基本上都是使用的System.Environment.CurrentDirectory。

但是最近在用另外一個程式A去呼叫以前的程式B的時候就出現問題了,程式A的作用只是單純調取程式B的exe檔案,在B執行過程中總是真到當前路徑這塊就出現了問題,實際找到的路徑是程式A的路徑。

程式A目錄:D:\a
程式B目錄:D:\b
當程式A呼叫程式B時,程式B中的Environment.CurrentDirectory結果是D:\a,而不是D:\b!!

當遇到這樣的情況時,我自己的解決方案是:

把所有System.Environment.CurrentDirectory改成System.AppDomain.CurrentDomain.BaseDirectory。

 

網上也有很多人說針對winform可以改成Application.StartupPath。

C# WinForm中AppDomain.CurrentDomain.BaseDirectory與Application.StartupPath的區別示例如下:

1. AppDomain.CurrentDomain.BaseDirectory 返回結果為: D:\xxx\
Application.StartupPath 返回結果為: D:\xxx
2. Application.StartupPath 只能用於WinForm窗體中,而AppDomain.CurrentDomain.BaseDirectory既可以用於WinForm窗體中,也可以用於類庫DLL檔案中。