17

I'm using Request.ApplicationPath to learn the name of the Virtual Directory in which I'm running. Is there a more reliable way?

lance
  • 16,092
  • 19
  • 77
  • 136
  • 3
    What makes `Request.ApplicationPath` unreliable? – Mehrdad Afshari Jan 30 '10 at 18:44
  • 1
    I never should have used the word "reliable". "Cleaner" would have been a better way. I'd like something that gave me the name (or alias) of the Virtual Directory without concerning me with the slash at the beginning. Petty, I know, but I don't mind asking these sorts of things. I'm sorry for my poor wording. – lance Jan 30 '10 at 21:42
  • 1
    Create a utility function to provide what you want. Of course, utilizing the Request.ApplicationPath to start with. – Clarence Klopfstein Feb 01 '10 at 22:28

3 Answers3

22

Request.ApplicationPath is perfectly reliable way of getting the virtual directory and works always when you have the HttpContext and can ask for the Request data.

For further processing and extracting parts of the path, take a look at the VirtualPathUtility class.

Tomas Vana
  • 18,317
  • 9
  • 53
  • 64
2

You need to use Request.ApplicationPath. That is what it is designed for.

Editing to go with your comment.

Since you want a 'cleaner' way to handle the slash, I recommend creating a utility function that returns the application path with the logic in it to deal with the slash as you see fit.

Clarence Klopfstein
  • 4,682
  • 10
  • 33
  • 47
1

Use this function in C#:

public static String GetHost()
{
    var request = HttpContext.Current.Request;
    return request.Url.Scheme + "://" + request.ServerVariables["HTTP_HOST"] + request.ApplicationPath;
}
Enamul Hassan
  • 5,266
  • 23
  • 39
  • 56