Knelis
Knelis

Reputation: 7159

Programmatically Access a File on ASP.NET MVC4

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?

Upvotes: 1

Views: 3450

Answers (3)

testCoder
testCoder

Reputation: 7385

Have you tried:

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

Upvotes: 1

Kinexus
Kinexus

Reputation: 12904

Use HttpContext.Current.Server.MapPath

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

Upvotes: 3

Asif Mushtaq
Asif Mushtaq

Reputation: 13150

use Server.MapPath to get the absolute path.

string path = Server.MapPath("/Documents/test.xml");
XDocument xml = XDocument.load(path);

Upvotes: 5

Related Questions