Get Application Path [C# / ASP.NET]

public string GetApplicationPath()
  {
   string applicationPath = "";

   if (this.Page.Request.Url != null)
    applicationPath = this.Page.Request.Url.AbsoluteUri.Substring( 
     0, this.Request.Url.AbsoluteUri.ToLower().IndexOf(
      this.Request.ApplicationPath.ToLower(), 
       this.Request.Url.AbsoluteUri.ToLower().IndexOf(
      this.Page.Request.Url.Authority.ToLower()) + 
      this.Page.Request.Url.Authority.Length) + 
     this.Request.ApplicationPath.Length);
  return applicationPath;
  }

Use this in any ASP.NET page to get the application path. For example, if you run this function in http://localhost/pathtest/test.aspx, the function will return http://localhost/pathtest/

Another way to redirect is to use the .NET tilde. For example, to navigate to the home page of your website from any place, you would do Response.Redirect(”“); or even /default.aspx.

  • Share/Bookmark

22 Comments

Sanat GersappaSeptember 26th, 2004 at 11:13 pm

If you’re using VB, you could use this function

Function GetApplicationPath()
Dim path As String = Left(Request.Url.AbsoluteUri, Request.Url.AbsoluteUri.Length + 1 – Request.Path.Length)
Return path
End Function

For redirecting, you can use /default.aspx…no ~ required.

Sanat GersappaSeptember 27th, 2004 at 12:11 am

Ok. I was feeling sleepy when I wrote the previous comment….it doesn’t work in a subfolder :-)

Here’s something in C# that should – I’m still sleepy, so I’m quite sure it can be written more elegantly –

public string GetApplicationPath()
{
string path = String.Empty;
string[] segs = Request.Url.Segments;

for (int i = 0; i < segs.Length – 1; i++)
{
path += segs[i];
}
return Request.Url.GetLeftPart(UriPartial.Authority) + path;
}

billsmithDecember 9th, 2004 at 1:32 pm

thank you but i think the bgcolor should bright!

mascixJanuary 11th, 2005 at 5:03 pm

I wanted to thank u this is so stupid why .NET framework doesnt have this kind of easy and usefull thing inside itself anyway thx guys

MikhailJanuary 25th, 2005 at 4:55 pm

mascix: If you are doing just a redirect, you can use ‘~’. For example:

Response.Redirect(”~/signup/join.aspx”);

IryxFebruary 26th, 2005 at 7:29 am


private string GetApplicationPath()
{
return HttpContext.Current.Request.Url.Host + HttpContext.Current.Request.ApplicationPath;
}

ChristianApril 6th, 2005 at 8:49 pm

I wrote something that uses less code

public static string GetUrlPath(System.Web.UI.Page sender)
{
string urlStr = sender.Request.RawUrl;
int pos = urlStr.LastIndexOf(”/”);
urlStr = urlStr.Substring(0,pos + 1);
return urlStr;
}

BenDecember 19th, 2005 at 7:33 pm

The last code block [GetUrlPath{System.Web.UI.Page sender)] worked for me while the other ones did not. I am not sure why this is the case.

Most mapped to the root of the C: drive and then attached the webserver path after that. The code posted by Sanat gave me a 404 error.

The last bit did not work by itself though. I ended up using something like this:

sXmlPath = @”\states.xml”;

XmlTextReader oXmlTxtRdr = new XmlTextReader(Server.MapPath(String.Concat(GetApplicationPath(this.Page), sXmlPath)).ToString());

BenDecember 19th, 2005 at 7:35 pm

Oh, sorry for the double comment, I forgot to mention that I renamed the function in the comment above mine to GetApplicationPath, and the code posted by Christian I used unchanged, I just needed some additional bits to get it to build the path for the XmlReader correctly.

KiranFebruary 9th, 2006 at 11:26 pm

Thanks Mikhail. Works great.

StevenNovember 30th, 2006 at 10:00 pm

I used this and it worked fine for asp.net / vb

dim path as string = Page.MapPath(”~/”) & “/App_Data/DataLists.xml”

JeyAr(MC)January 16th, 2007 at 12:16 am

Left(Request.Url.AbsoluteUri,request.Url.AbsoluteUri.LastIndexOf(”/”)+1)

return the path of you current file

RalphJanuary 25th, 2007 at 3:07 am

Have any of you considered a path such as
http://localhost/file.aspx/a/b/c/d/e/
where “file.aspx” is your actual script?

At first sight, the only one to work correctly would be Iryx’s.

DonnyJanuary 20th, 2008 at 7:09 pm

string applicationUrl = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + HttpContext.Current.Request.ApplicationPath + “/”;

Works like a charm :)

KenApril 2nd, 2008 at 1:12 am

This requires less code:

Request.Url.AbsoluteUri.Substring(0, Request.Url.AbsoluteUri.LastIndexOf(”/”))

Allan McLemoreApril 5th, 2008 at 10:41 pm

I’ll have to try this methodology. You can use Singleton pattern on this and persist the Application path in an object property. That way the evaluation only happens once in each application instance.

I took a slightly different approach to solving this issue. When you try to generate Urls using the various values built into ASP.NET (ApplicationPath, “~”, etc), you will encounter problems in some scenarios.

Check out my post on this issue: http://www.zenternal.com/weblog/?p=6

The code sample provided in my article does not address the issue with ASP.NET returning localhost when running on XP Workstation. However, the URL methodology in the code can be improved to use System.Environment.MachineName whenever Request.ServerVariables[“SERVER_NAME”] returns localhost. I’ll try to post an update to the article soon.

Gauthier SegayJuly 14th, 2008 at 1:29 am

This is so scary how unfriendly ASP.NET can be…

I’ve refactored the function to something that is Page agnostic and with less duplication of unecessary property access:

public string GetApplicationAbsolutePath(Uri requestUri, string siteRootRelativeApplicationPath) {
string
requestAbsoluteUri = requestUri.AbsoluteUri,
requestAuthority = requestUri.Authority;
return
requestAbsoluteUri.Substring(0,
requestAbsoluteUri.IndexOf(
siteRootRelativeApplicationPath.ToLower(),
requestAbsoluteUri.IndexOf(
requestAuthority,
StringComparison.InvariantCultureIgnoreCase
)
+ requestAuthority.Length,
StringComparison.InvariantCultureIgnoreCase
)
+ siteRootRelativeApplicationPath.Length
);
}

Quang VoSeptember 24th, 2008 at 3:02 pm

You can try it this way and it works great. http://connectionstringexamples.com/article.php?story=20080924032917497

Steve71October 17th, 2008 at 8:01 pm

My personal method, not as short as others, but fail-proof and ultra-tested. Bye!

public static class clsHTTPManager
{
public static string GetApplicationUrl()
{
HttpContext ctx = HttpContext.Current;

string toReturn = (string)ctx.Cache.Get(“ApplicationUrl”);

if (String.IsNullOrEmpty(toReturn))
{
string protocol = ctx.Request.ServerVariables.Get(“SERVER_PORT_SECURE”);
string port = ctx.Request.ServerVariables.Get(“SERVER_PORT”);
string host = ctx.Request.ServerVariables.Get(“SERVER_NAME”);

if (protocol.Equals(“off”, StringComparison.OrdinalIgnoreCase) || protocol.Equals(“0”))
protocol = “http://”;
else
protocol = “https://”;

if (port.Equals(“80”))
port = String.Empty;
else
port = “:” + port;

toReturn = String.Format(”{0}{1}{2}{3}”, protocol, host, port, ctx.Request.ApplicationPath);

ctx.Cache.Insert(“ApplicationUrl”, toReturn);
}

return toReturn;
}
}

eokNovember 25th, 2008 at 4:06 am

Request.Url.GetLeftPart(UriPartial.Authority) + Page.ResolveUrl(”~/Page.aspx”)

NAMEJune 10th, 2009 at 8:40 am

Save yourselves some time:
HttpContext.Current.Request.PhysicalApplicationPath

arashOctober 10th, 2009 at 5:56 pm

string relative = System.Web.HttpContext.Current.Request.Url.AbsoluteUri;
relative = relative.Substring(0, relative.LastIndexOf(”/”));

Leave a comment

Your comment