Getting the Virtual Path of a Request in c#

This simple bit of code will get you the Virtual Path of your current request.

public static string GetVirtualPath(string url)
{
    if (HttpContext.Current.Request.ApplicationPath == "/")
    {
        return "~" + url;
    }

    return Regex.Replace(url, "^" + 
                   HttpContext.Current.Request.ApplicationPath + "(.+)$""~$1");
}

Example Usage

 // the Url is http://www.GeekZilla.co.uk/DemoApp/default.aspx
 // and in my instance, DemoApp is the root of the application

 string myVirtualPath = GetVirtualPath(HttpContext.Current.Request.Raw));

 // the result would be ~/default.aspx

Notes

Don't forget to include:

using System.Text.RegularExpressions;
Author Paul Hayman

Paul is the COO of kwiboo ltd and has more than 20 years IT consultancy experience. He has consulted for a number of blue chip companies and has been exposed to the folowing sectors: Utilities, Telecommunications, Insurance, Media, Investment Banking, Leisure, Legal, CRM, Pharmaceuticals, Interactive Gaming, Mobile Communications, Online Services.

Paul is the COO and co-founder of kwiboo (http://www.kwiboo.com/) and is also the creator of GeekZilla.

Comments

Dima Pasko said:

08/Nov/2007 10:35 AM

phayman said:

ah .. I missed that.. I'm going to have a play with it .. especially the VirtualPathUtility.ToAppRelative() method

14/Jan/2008 17:42 PM

Add Comment

Name
Comment
 

Your comment has been received and will be shown once it passes moderation.