1

As part of an ASP.NET MVC4 project I need to be able to read from and write to some XML files. I have trouble finding / accessing the files I need.

I've created a demo project to which I've added a folder /Documents containing some XML files.

So in the same project I have a folder /Classes with my class that should read the XML files using XDocument.load().

Here is what I'd like to do (and how I thought it should work):

string path = "/Documents/test.xml"; // Doesn't work
XDocument xml = XDocument.load(path);

However, this doesn't work. Not with "/Documents", "Documents" or "~/Documents". Supplying the full path works, but not very useful if the website is going to be deployed in other environments.

string path = "D:/Projects/Demo/Demo/Documents/test.xml"; // Works
XDocument xml = XDocument.load(path);

Any suggestions how I can access the files using some kind of relative path?

3 Answers 3

5

use Server.MapPath to get the absolute path.

string path = Server.MapPath("/Documents/test.xml");
XDocument xml = XDocument.load(path);
Sign up to request clarification or add additional context in comments.

Comments

3

Use HttpContext.Current.Server.MapPath

string path = HttpContext.Current.Server.MapPath("/Documents/test.xml"); 

Comments

1

Have you tried:

var path = Server.MapPath("/Documents/test.xml");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.