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 |
| 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.