Relative paths in ASP.NET application code

As a newbie to ASP.NET, I'm not sure about the best solution to my problem. I have a line of code like:

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

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

How to correctly point to this directory without hard coding?

+6
source share
5 answers

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

xDoc.Load(Server.MapPath("~/Templates/template.cfg"));
+17
source

I would probably use

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

XML ASP.NET. , , Windows Forms, , Windows Forms.

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

?

+3
source

Try:

xDoc.Load(Server.MapPath("~/Templates/template1.cfg"));
+3
source

Use the tilde "~" in your path.

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

Tilda represents the base directory for your application.

+1
source

All Articles