繁体   English   中英

为什么System.AppDomain.CurrentDomain.BaseDirectory返回不同的结果?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM