![](/img/trans.png)
[英]Why is AppDomain.CurrentDomain.BaseDirectory targeting bin catelog in console application?
[英]Why does System.AppDomain.CurrentDomain.BaseDirectory return different results?
我在app.config中存儲了我的數據庫路徑(包含一些xml文件的文件夾)。 在啟動時我檢查,如果路徑存在。 如果它不存在,我想將路徑設置為默認路徑。 代碼如下所示:
public void CheckAndRepairSettings()
{
/* Check Paths */
if(GetDatabasePath() == null)
SetDatabasePath(System.AppDomain.CurrentDomain.BaseDirectory + "DataBase");
}
GetDatabasePath()
從app.config讀取路徑, SetDatabasePath()
將路徑寫入app.config。 這些方法工作正常。
我的問題是System.AppDomain.CurrentDomain.BaseDirectory
。 如果我在我的應用程序調試模式下運行它,我得到:“F:\\ Office \\ Projekte_Software \\ ServiceTool \\ _Work \\ ServiceSoftware \\ ServiceSoftware \\ bin \\ Debug \\”
我還使用NUnit進行一些單元測試。 如果我在調試模式下運行NUnit,我得到:“F:\\ Office \\ Projekte_Software \\ ServiceTool \\ _Work \\ ServiceSoftware \\ ServiceSoftware.UnitTests \\ bin \\ Debug”
在NUnit調試模式下,路徑中沒有尾部反斜杠“\\”,因此當我在CheckAndRepairSettings()
連接路徑字符串時,我得到一個不存在的路徑。
為什么這個行為如此不同?
您應該使用Path.Combine來連接路徑,它處理有關現有/不存在(以及其他)路徑分隔符的問題
為什么一個包含結束斜杠而另一個不包括可能與nUnit如何創建運行其測試的appdomain有關
更好的選擇是使用IsolatedStorage
!
例如,您可以使用以下方法編寫設置:
using(IsolatedStorageFile f=IsolatedStorageFile.GetUserStoreForDomain())
{
using(var s=new IsolatedStorageFileStream("Myapp.config",FileMode.Create,f))
using(var writer=new StreamWriter(s))
writer.WriteLine("My Settings");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.