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?
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.
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.
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.
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).
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"));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With