ASP.Net Host

Get Application Root

I always need to get either the base url of the site or base folder (web root) of the domain so I can either find a file, or save a file to a folder. The following code is in almost every application that I ever write, so feel free to use it in your ASP.Net application if it helps.

//This function returns the Application path, like http://www.JoesWebsite.com/, or if the project is running in a virtual directory it returns the Application path of the virtual directory, like http://www.JoesWebsite.com/forums/ .

public static string ApplicationPath
{
   get
   {
      string APP_PATH = System.Web.HttpContext.Current.Request.ApplicationPath.ToLower();
      if(APP_PATH == "/")      //a site
         APP_PATH = "/";
      else if(!APP_PATH.EndsWith(@"/")) //a virtual
         APP_PATH += @"/";

      return APP_PATH;

   }
}


 

This function returns the Mapped path, like "D:\Hosting\Smith\JoeSmithWebsite\"

public static string MappedApplicationPath
{
   get
   {
      string APP_PATH = System.Web.HttpContext.Current.Request.ApplicationPath.ToLower();
      if(APP_PATH == "/")      //a site
         APP_PATH = "/";
      else if(!APP_PATH.EndsWith(@"/")) //a virtual
         APP_PATH += @"/";

      string it = System.Web.HttpContext.Current.Server.MapPath(APP_PATH);
      if(!it.EndsWith(@"\"))
         it += @"\";
      return it;
   }
}

So how do you get the correct relative URL when you are in the html view? If you want to use server controls then there is the famous "~/folder/file" method, which is great because this allows you to get the application path and it works when being called from a page in the root of your site, or when used in a page in a subfolder, but it can only be used by Server Controls (ie: "<asp:Image id=myImage runat=Server imageurl="~/images/smile.gif" />"), but if you don't want to use a server control, you can use the code below in the Global.asax file's Session_Start function as shown below. When you add a Global.asax file to your project, the Session_Start function is already there, so you just add the inner function code.

void Session_Start(Object sender, EventArgs e)
{
 

   // Code that runs when a new session is started
   string APP_PATH = System.Web.HttpContext.Current.Request.ApplicationPath.ToLower(); 
   if (APP_PATH == "/") //a site 
      APP_PATH =
"/";
   else if (!APP_PATH.EndsWith(@"/")) //a virtual 
      APP_PATH +=
@"/";
   Session[
"APP_Path"] = APP_PATH;  //stores the value to a session variable for us to use
}

Now, to use the session variable "APP_Path" that you've created in an html page, you will write your image tags like this:

<img src="<%=Session["APP_Path"] %>images/smile.gif" />

You can also get the value in your code-behind by accessing the session variable:

 string myPath = Session["APP_Path"].ToString();

 

0 Comments

We recommend Aquest Hosting for your ASP.Net 2.0 hosting, Community Server hosting, and DotNetNuke hosting.