簡體   English   中英

我應該使用 AppDomain.CurrentDomain.BaseDirectory 還是 System.Environment.CurrentDirectory?

[英]Should I use AppDomain.CurrentDomain.BaseDirectory or System.Environment.CurrentDirectory?

我在同一個文件夾中有兩個 exe 文件,我可以從 exe1 中的一個按鈕運行 exe2。 今天我通過遠程(終端服務)session 觀察客戶,exe2 未能運行“找不到文件”錯誤,但我們檢查時 exe1 在同一目錄中。 那么我應該使用AppDomain.CurrentDomain.BaseDirectory還是System.Environment.CurrentDirectory

謝謝

如果您想在與您的應用程序相同的目錄中查找文件, AppDomain.CurrentDomain.BaseDirectory是正確的選擇。

Environment.CurrentDirectory是一個可以並且將在運行應用程序的過程中發生變化的值。 例如,使用默認參數,WinForms 中的 OpenFileDialog 會將此值更改為從中選擇文件的目錄。

AppDomain.CurrentDomain.BaseDirectory返回加載當前應用程序域的目錄。
System.Environment.CurrentDirectory返回當前系統目錄。
在您的情況下, AppDomain.CurrentDomain.BaseDirectory是最好的解決方案。

您應該使用AppDomain.CurrentDomain.BaseDirectory

例如,在 windows 服務應用程序中:

System.Environment.CurrentDirectory將返回C:\Windows\system32

盡管

AppDomain.CurrentDomain.BaseDirectory將返回 [Application.exe 位置]

另一個需要注意的重要因素是AppDomain.CurrentDomain.BaseDirectory是一個只讀屬性,而Environment.CurrentDirectory可以是其他必要的屬性:

// Change the directory to AppDomain.CurrentDomain.BaseDirectory
Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;   

據我了解,您應該使用BaseDirectory CurrentDirectory可能會在程序執行過程中發生變化。

在 Visual Studio 2010 測試項目中,如果啟用編輯測試設置的部署選項,AppDomain.CurrentDomain.BaseDirectory 指向 TestResults\Out 文件夾(不是 bin\debug)。 雖然,默認設置指向 bin\debug 文件夾。

在這里,我找到了令人信服的答案。

為什么 AppDomain.CurrentDomain.BaseDirectory 在 asp.net 應用程序中不包含“bin”?

我也經歷了這幾天,因為我正在使用

Environment.CurrentDirectory

因為它在生產服務器上給了我問題,但在我的本地服務器上運行良好,

所以,我嘗試了

System.AppDomain.CurrentDomain.BaseDirectory;

它在環境中都對我有用。

所以,正如所有人所說,我們應該始終使用 go

System.AppDomain.CurrentDomain.BaseDirectory;

因為它檢查當前域目錄的路徑。

查看更多信息

在服務器上找不到部分路徑錯誤

我通常使用類似的東西:

            string AppPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
            AppPath = AppPath.Replace("file:\\", "");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM