load file from relative path

I am currently doing this:

XDocument feedXml = XDocument.Load("C:/NewsFeed/NewsFeed/App_Data/WorldNews.xml");

But I'd like to use a relative path, so I I've tried the following:

XDocument feedXml = XDocument.Load("~/App_Data/WorldNews.xml");

And set the property, Copty to Output Directory, to "Copy Always".

But I'm getting the following error:

An exception of type 'System.IO.DirectoryNotFoundException' occurred in mscorlib.dll but was not handled in user code Additional information: A part of the path 'C:\Program Files (x86)\IIS Express\~\App_Data\WorldNews.xml' was not found.

Any help please?

Upvotes: 0

Views: 2327

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503310

XDocument.Load doesn't know anything about mapping paths. Instead, you should use HttpServerUtility.MapPath to map the path, then pass the result into XDocument.Load:

var path = HttpContext.Current.Server.MapPath("~/App_Data/WorldNews.xml");
var feedXml = XDocument.Load(path);

Upvotes: 4

Related Questions