kmarks2
kmarks2

Reputation: 4875

Relative paths in an ASP.NET application code behind

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?

Upvotes: 8

Views: 28390

Answers (5)

to StackOverflow
to StackOverflow

Reputation: 124686

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.

Upvotes: 12

Adrian Iftode
Adrian Iftode

Reputation: 15663

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"));

Upvotes: 20

JDunkerley
JDunkerley

Reputation: 12495

Try:

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

Upvotes: 3

Khan
Khan

Reputation: 18142

Use a tilde "~" in your path.

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

The tilde represents the base directory for your application.

Upvotes: 1

mattematico
mattematico

Reputation: 669

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

might work?

Upvotes: 3

Related Questions