Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relative paths in an ASP.NET application code behind

Tags:

c#

.net

asp.net

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?

like image 369
kmarks2 Avatar asked Mar 07 '12 14:03

kmarks2


People also ask

How do I use relative path in ASP NET?

By default, browsers resolve relative paths by using the current page URL as the base. However, you can include an HTML base element in a page to specify an alternate base path. In ASP.NET server controls that reference resources, you can use absolute or relative paths as you do for client elements.

What is mappath () in ASP NET?

The latter function is sort of like a Server.MapPath () but for mapping a logical path to a purely application relative path. Certainly this is not your typical everyday function, but it comes up occasionally for generic tools and handlers that serve data that are specific to a given ASP.NET host request.

What is the use of file path in ASP NET?

Similarly, code in your Web application might use a physical file path to a server-based file to read or write the file. ASP.NET provides facilities for referring to resources and for determining the paths of pages or other resources in the application.

What is the difference between absolute and relative path?

An absolute URL path. An absolute URL path is useful if you are referencing resources in another location, such as an external Web site. A site-root relative path, which is resolved against the site root (not the application root).


2 Answers

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"));
like image 61
Adrian Iftode Avatar answered Nov 15 '22 06:11

Adrian Iftode


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.

like image 43
Joe Avatar answered Nov 15 '22 06:11

Joe