在 Visual Studio2017 中加载动态生成的 XML 文件的最佳选择是什么

问题描述

我有一个读取 xml 文件的类库项目。 xml 文件将不时动态更新。因此,我没有将 Visual Studio 中的 xml 文件设置为 Build Action = Embedded Resource,因为它每次都需要编译。

现在,如果我通过获取相对路径将其作为外部源读取。这是我用来读取文件代码

public static string GetDatabaseXMLPath()
{
    string LPath = string.Empty;
    try
    {
        string Location = AppDomain.CurrentDomain.BaseDirectory;

        int index;
        int len;

        index = Location.IndexOf("MyProject");
        len = Location.Length;

        if (index > 0)
        {
            LPath = Location.Remove(index,len - index);
            LPath = LPath + "MyProject\\DatabaseInfoFile\\Database.xml";
        }
        else
        {
            LPath = Location;
        }
        Console.WriteLine(LPath);
    }

    catch (Exception e)
    {
        Console.WriteLine("Error in GetDatabaseXMLPath " + e);
    }

    return LPath;
}

上面的代码工作正常,我可以通过同一解决方案中的控制台测试项目读取它。 问题是当我用这个 Dll 创建一个 Nuget 包并在另一个项目中使用它时,比如 Project-2。 另一个 Project-2 显示错误,就像在其自己的 bin 目录中而不是在 Dll 的目录中查找文件一样。

System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\My Projects\Project-2\Project-2\bin\Debug\'.

到目前为止,它仅在我在 Dll 中使用绝对路径时才有效。

const string FILENAME = @"\FileName\Database.xml";

并将其读作:

XDocument doc = XDocument.Load(FILENAME);

dll 将放置在服务器(dev/uat/prod)上,所以请告知是否有更好的解决方案。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)