Get full path to file while debugging using IIS Express
Asked Answered
S

1

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.

Shriver answered 8/11, 2012 at 18:20 Comment(2)
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.Faretheewell
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.Shriver
G
8

Use Server.MapPath:

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

or HttpServerUtility.MapPath:

HttpServerUtility.MapPath("~/_templates/myFile.html")
Gorse answered 8/11, 2012 at 18:23 Comment(2)
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.Shriver
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();Crapulent

© 2022 - 2024 — McMap. All rights reserved.