Reputation: 4875
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
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
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
Reputation: 18142
Use a tilde "~" in your path.
xDoc.Load("~/Templates/template1.cfg");
The tilde represents the base directory for your application.
Upvotes: 1