5

I have a static class in a folder off root in my solution. In that static class' folder, there's a subfolder containing XML files. So I've got these files:

/PartialViews/Header/MyStaticClass.cs
/PartialViews/Header/Config/en-US.xml
/PartialViews/Header/Config/jp-JP.xml
...

I'm having trouble using XDocument.Load() with those XML files. Specifically, I'm trying to load the XML files from the static constructor of MyStaticClass.

XDocument.Load() can't seem to find the files, however. I've tried all these and none work:

static MyStaticClass()
{
    XDocument doc;

    // These all throw exceptions relating to directory not found
    doc = XDocument.Load("/Config/en-US.xml");
    doc = XDocument.Load(@"\Config\en-US.xml");
    doc = XDocument.Load("/PartialViews/Header/Config/en-US.xml");
    doc = XDocument.Load(@"\PartialViews\Header\Config\en-US.xml");
}

I also tried using Assembly.GetExecutingAssembly().Location and Assembly.GetEntryAssembly().Location before the relative path, but the assembly resolved by Assembly is always a .NET library (because the type is being initialized?).

How can I load the file without changing its location in the solution?

1
  • Please leave tags like "C#" in the tags, and keep them out of the title. No reason to have the same information in two places. Commented Sep 14, 2010 at 19:08

2 Answers 2

6

In ASP.NET you should use Server.MapPath() to find all local files.

string relPath = "~/PartialViews/Header/Config/en-US.xml";
string absPath = Server.MapPath(relPath);

XDocument doc = XDocument.Load(absPath);
Sign up to request clarification or add additional context in comments.

Comments

1

For .NET web apps use HttpContext.Current.Server.MapPath("~/"); this will get you the root directory of the executing file.

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.