7

Being new to ASP.NET I'm unsure of the best solution to my problem. I have a line of code like:

xDoc.Load("Templates/template1.cfg");

xDoc is an XmlDocument. In my project, at the top level there is a directory called Templates. When I run the project in debug mode, I get a DirectoryNotFoundException, and apparently it's looking for the Templates dir in C:\Program Files\Common Files\Microsoft Shared\DevServer\10.0\Templates.

How can correctly point to that directory without hardcoding it?

1
  • 6
    Have you looked at Server.MapPath ?
    – asawyer
    Mar 7, 2012 at 14:18

5 Answers 5

19

Server.MapPath - returns the path of the relative path; ~ ensures the relative path is related to the application root

xDoc.Load(Server.MapPath("~/Templates/template.cfg"));
0
12

I would probably use

xDoc.Load(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Templates", "Template.cfg"));

This makes your XML loading code independent of ASP.NET. If you were to reuse it in, say, a Windows Forms application, this would give a path relative to the directory containing the Windows Forms exectuable.

3
xDoc.Load("~/Templates/template.cfg");

might work?

3

Try:

xDoc.Load(Server.MapPath("~/Templates/template1.cfg"));
1

Use a tilde "~" in your path.

xDoc.Load("~/Templates/template1.cfg");

The tilde represents the base directory for your application.

2
  • Unfortunately that was what I tried first, with the same problem. Which is odd because ~/ works fine in the aspx pages.
    – kmarks2
    Mar 7, 2012 at 14:19
  • Yeah - xDoc won't know it's being used in the context of an ASP.NET app. Check out Server.MapPath.
    – n8wrl
    Mar 7, 2012 at 14:21

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.