Friday, February 27, 2009

How to get the the Application Path in asp.net applications Irrespective of production or live environment?

1. Create the following class under the App_Code folder.
public sealed class ApplicationPath
{
#region Private Constructor

///
/// Prevents a default instance of the ApplicationPath class from being created
///

private ApplicationPath()
{
}

#endregion

///
/// Gets the current application path
///

///
public static string GetApplicationPath
{
get
{
string port = System.Web.HttpContext.Current.Request.ServerVariables["SERVER_PORT"];
if (port == null || port == "80" || port == "443")
{
port = string.Empty;
}
else
{
port = ":" + port;
}

string protocol = System.Web.HttpContext.Current.Request.ServerVariables["SERVER_PORT_SECURE"];
if (protocol == null || protocol == "0")
{
protocol = "http://";
}
else
{
protocol = "https://";
}

string p = protocol + System.Web.HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + port + System.Web.HttpContext.Current.Request.ApplicationPath;
p = p.Trim();
if (!p.EndsWith("/"))
{
p += "/";
}

return p;
}
}
}

2. Use the ApplicationPath.GetApplicationPath to get the application path.

No comments:

Post a Comment