在C#中加载XML文件路径

Tob*_*and 9 .net c# xml path visual-studio-2012

我正在尝试加载位于项目文件夹中的XML文件(使用Visual Studio 2012).

结构是这样的:

solutionRoot\
-  service\
--   ServiceClass.cs
--   AppValues.xml  <-- this is the file I want to load
Run Code Online (Sandbox Code Playgroud)

在我的ServiceClass中,我尝试使用以下代码从XML文件中读取:

public String GetXmlElement(String elementName)
{
    [....]
    XDocument document = XDocument.Load(@"\service\AppValues.xml");
    [...]
}
Run Code Online (Sandbox Code Playgroud)

当我尝试测试代码时,会出现以下错误:

Test method PandaTests.ServiceTest.ReadXmlCanReadXml threw exception: 
System.IO.DirectoryNotFoundException: Could not find a part of the path 
'C:\Users\MyName\Documents\GitHub\project\Project22\PandaTests\bin\Debug\service\AppValues.xml'.
Run Code Online (Sandbox Code Playgroud)

这显然是我的路径的问题,但我无法弄清楚如何使相对路径正确.我在这里查看了有关堆栈溢出的其他问题,但其中许多似乎过度参与.是否有一种简单的方法来加载XML文件而不提供绝对路径?

Tyl*_*Lee 14

当VS运行您的程序时,您的工作目录将设置为Debug/Release文件夹,而不是您的解决方案根目录.

你知道几个选项......

  1. 使用绝对路径,但您不希望这样
  2. 将文件设置为在构建时复制到工作目录中.您可以通过在解决方案资源管理器中修改文件的属性来执行此操作. 感谢T.Roland在下面的评论中:将Copy to Set Directory设置为Copy to new,并将Build Action设置为Embedded Resource;
  3. 修改您的解决方案的工作目录以成为您的解决方案根该线程提供了不同的方法来实现它.

  • 我建议编辑扩展第二点(要设置的属性)基本上:A)设置**复制到输出目录**到*复制如果更新*; B)将**Build Action**设置为*Embedded Resource*; C)现在可以使用`XDocument.Load(@"service\AppValues.xml")加载文件. (4认同)