Why does System.AppDomain.CurrentDomain.BaseDirectory return different results?

爷,独闯天下 提交于 2020-01-14 19:23:07

问题


I store the path of my database (a folder with some xml files) in the app.config. At the startup I check, if the path exists. If it doesn't exist, I want to set the path to the default path. Code looks like this:

public void CheckAndRepairSettings()
{
        /* Check Paths */
        if(GetDatabasePath() == null)
             SetDatabasePath(System.AppDomain.CurrentDomain.BaseDirectory + "DataBase");
}

GetDatabasePath() reads the path form the app.config and SetDatabasePath() writes the path to the app.config. These Methods are working fine.

My promblem is the System.AppDomain.CurrentDomain.BaseDirectory. If I run this in my applications debug mode I get: "F:\Office\Projekte_Software\ServiceTool\_Work\ServiceSoftware\ServiceSoftware\bin\Debug\"

I additionally use NUnit for some unit tests. If I run NUnit in debug mode I get : "F:\Office\Projekte_Software\ServiceTool\_Work\ServiceSoftware\ServiceSoftware.UnitTests\bin\Debug"

There is no trailing Backslash "\" in the path in NUnit debug mode, so I get a non existing path when I concatenate the path-string in my CheckAndRepairSettings().

Why does this behave so different?


回答1:


You should use Path.Combine to concatenate paths, it handles issues regarding existing/non-existing (among other things) path separators

Why one includes ending slash the other one doesn't is probably related to how nUnit creates the appdomain under which it runs its tests




回答2:


A better option would be to use IsolatedStorage!

For Example you can write settings using this:

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");
}


来源:https://stackoverflow.com/questions/11720587/why-does-system-appdomain-currentdomain-basedirectory-return-different-results

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!