Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading an XML file path in C#

I'm trying to load an XML-file, located in a folder in my project (using Visual Studio 2012).

The structure is this:

solutionRoot\
-  service\
--   ServiceClass.cs
--   AppValues.xml  <-- this is the file I want to load

In my ServiceClass, I'm trying to read from the XML-file with the following code:

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

Which gives the following error, when I'm trying to test the code:

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'.

It's obviously a problem with my path, but I can't figure out how to get the relative path right. I've looked at other questions here on stack overflow, but many of them seem overly involved. Is there an easy way to load the XML-file without giving an absolute path?

like image 441
Tobias Roland Avatar asked Nov 13 '13 15:11

Tobias Roland


3 Answers

When VS runs your program, your working directory is set to the Debug/Release folder, not to your solution root.

You have a couple options that I know of...

  1. Use an absolute path, but you don't want this
  2. Set your file to copy into your working directory on build. You do this by modifying the properties of the file in the solution explorer. Thanks to T.Roland in the comments below: Set Copy to Output Directory to Copy if Newer and set Build Action to Embedded Resource;
  3. Modify your solution's working directory to be your solution root This thread offers different ways to accomplish that.
like image 131
Tyler Lee Avatar answered Nov 18 '22 22:11

Tyler Lee


I faced the same problem and solved it using "Server.MapPath"

For example,

string path=Server.MapPath("~/service/AppValues.xml");

XDocument document = XDocument.Load(path);

Hope it helps.

like image 26
Sarath Rachuri Avatar answered Nov 18 '22 22:11

Sarath Rachuri


Bring up the properties in Visual Studio for AppValues.xml. Change "Copy to Output Directory" to "Copy if Newer", and build the project.

like image 2
jlew Avatar answered Nov 18 '22 23:11

jlew