Search code examples
c#asp.net.neturl

How to get URL path in C# .Net from the HttpContext


I want to get the all the path of URL except the current page of url, eg: my URL is http://www.MyIpAddress.com/red/green/default.aspx I want to get "http://www.MyIpAddress.com/red/green/" only. How can I get.I'm doing like

string sPath = new Uri(HttpContext.Current.Request.Url.AbsoluteUri).OriginalString; System.Web.HttpContext.Current.Request.Url.AbsolutePath;
            sPath = sPath.Replace("http://", "");
            System.IO.FileInfo oInfo = new System.IO.FileInfo(sPath);
            string sRet = oInfo.Name;
            Response.Write(sPath.Replace(sRet, ""));

Its showing exception on new System.IO.FileInfo(sPath) as sPath contain "localhost/red/green/default.aspx" saying "The given path's format is not supported."


Solution

  • Don't treat it as a URI problem, treat it a string problem. Then it's nice and easy.

    String originalPath = new Uri(HttpContext.Current.Request.Url.AbsoluteUri).OriginalString;
    String parentDirectory = originalPath.Substring(0, originalPath.LastIndexOf("/"));
    

    Really is that easy!

    Edited to add missing parenthesis.