GeekZilla
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;
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:
What about VirtualPathUtility class http://msdn2.microsoft.com/en-us/library/system.web.virtualpathutility.aspx
phayman
said:
ah .. I missed that.. I'm going to have a play with it .. especially the VirtualPathUtility.ToAppRelative() method