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?
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...
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.
Bring up the properties in Visual Studio for AppValues.xml. Change "Copy to Output Directory" to "Copy if Newer", and build the project.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With