7

I have a .NET application that I am trying to debug and part of my application loads a file from my project. This file is located at

C:\Users\USER_FOLDER\Documents\Visual Studio 2012\Projects\MY_PROJECT\_templates\myFile.html

In my code, I specify a relative path to the file and use the DirectoryInfo class to get the full directory path to my file:

string myFile = (new DirectoryInfo("_templates/myFile.html")).FullName;

However, this returns the following path (extra \'s as escape characters):

"C:\\Program Files\\IIS Express\\_templates\\myFile.html"

I was expecting the path that is returned when debugging in IIS Express would match the first path I listed, not the third. Why is this? Is there something else that I need to set up in my project to have it derive the paths properly? I'm assuming that this would not happen if I deployed my code to a IIS7 site, but I haven't gotten to that testing level yet.

Anil
  • 2,539
  • 6
  • 33
  • 42
  • If its returning `Program Files\\IIS Express\\` it means your launching it from that directory path so be more specific about the directory path. Considering `"_templates/myFile.html" would be a local directory within the parent directory its not very specific. – Security Hound Nov 08 '12 at 19:29
  • On that note, calling Server.MapPath returned the correct path without having to be more descriptive. Going into this I didn't think I had to be more descriptive because as in other languages, I was treating the path as it was relative to the location of the script that was referencing the file, but in order to read its contents the .NET server needs a Fully Qualified URI to the path and I was just using the wrong Object to derive it. Why my _valid_ question was voted down is perplexing. – Anil Nov 08 '12 at 20:25

1 Answers1

7

Use Server.MapPath:

Server.MapPath("~/_templates/myFile.html")

or HttpServerUtility.MapPath:

HttpServerUtility.MapPath("~/_templates/myFile.html")
John Weisz
  • 30,137
  • 13
  • 89
  • 132
Knaģis
  • 20,827
  • 7
  • 66
  • 80
  • Thanks! Server.MapPath worked for me, but I couldn't get HttpServerUtility.MapPath to work. For HttpServerUtility it kept complaining that `An object reference is required for the non-static field, method, or property 'System.Web.HttpServerUtility.MapPath(string)'` I tried various ways of writing it and nothing worked, so I'm going to just use Server.MapPath. Thanks again. – Anil Nov 08 '12 at 18:36
  • 6
    Not sure if this is the exact same situation but I had the same object reference problem. I solved it using the HttpContext. As in - HttpContext.Current.Server.MapPath(); – Peter Rasmussen Mar 11 '17 at 10:12