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文件中。


免責聲明!

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



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