You are not Logged in
Would you like to Login or Register

Today is: Friday, 21 November, 2008
Check this months hot topics

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;
kick it on DotNetKicks.com del.icio.us digg Mister Wong YahooMyWeb Reddit Furl Spurl blogmarks
Paul Hayman Skype
Author : Paul Hayman
Published : Monday, 05 November, 2007

Paul is the COO of kwiboo ltd consultant and has more than a decade of 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:

November 08, 2007 - 10:35 AM

phayman said:

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

January 14, 2008 - 5:42 PM

Add Comment

Enter your comment below and it will be submitted for moderation.

Your Name

Add Tag

Please enter tags for this article, seperated by semi-colon ;

View Tag's by : # articles | # views