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.


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.
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;
}
thank you but i think the bgcolor should bright!
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
mascix: If you are doing just a redirect, you can use ‘~’. For example:
Response.Redirect(”~/signup/join.aspx”);
private string GetApplicationPath()
{
return HttpContext.Current.Request.Url.Host + HttpContext.Current.Request.ApplicationPath;
}
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;
}
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());
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.
Thanks Mikhail. Works great.
I used this and it worked fine for asp.net / vb
dim path as string = Page.MapPath(”~/”) & “/App_Data/DataLists.xml”
Left(Request.Url.AbsoluteUri,request.Url.AbsoluteUri.LastIndexOf(”/”)+1)
return the path of you current file
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.
string applicationUrl = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + HttpContext.Current.Request.ApplicationPath + “/”;
Works like a charm :)
This requires less code:
Request.Url.AbsoluteUri.Substring(0, Request.Url.AbsoluteUri.LastIndexOf(”/”))
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.
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
);
}
You can try it this way and it works great. http://connectionstringexamples.com/article.php?story=20080924032917497
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;
}
}
Request.Url.GetLeftPart(UriPartial.Authority) + Page.ResolveUrl(”~/Page.aspx”)
Save yourselves some time:
HttpContext.Current.Request.PhysicalApplicationPath
string relative = System.Web.HttpContext.Current.Request.Url.AbsoluteUri;
relative = relative.Substring(0, relative.LastIndexOf(”/”));