Friday, 5 June 2015

Application current folder in Asp.net C#

There are various predefined functions are available in Asp.net by using which we could find out the directory location , few are

  • HttpContext.Current.Server.MapPath()
    • Current Web application root directory. Generally call by web page for current incoming request.
  • Application.StartupPath
    • Execution folder of  windows or standalone console program.
  • System.Reflection.Assembly.GetExecutingAssembly().Location()
    • returns where the executing assembly is currently located, which may or may not be where the assembly is located when not executing. In the case of shadow copying assemblies, you will get a path in a temp directory. 
  • AppDomain.CurrentDomain.BaseDirectory
    • when I want to find a path relative to an applications folder. This works for both ASP.Net and winform applications. It also does not require any reference to System.Web assemblies.
  • System.IO.Path.GetDirectoryName()
    • Once we will have the path , will get the directory.
  • System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase()
    • To get the location the assembly normally resides on disk or the install directory. It will return the 'permanent' path of the assembly.
  • System.IO.Path.GetDirectory(Application.ExecutablePath)
    • Get full path of directory where application executes.


AppDomain.CurrentDomain.BaseDirectory()  is probably the most useful for accessing files whose location is relative to the application install directory.


Some interesting way in Web application
protected void Application_Start(object sender, EventArgs e)
{
  string p1 = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
  string p2 = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
  string p3 = this.Server.MapPath("");
  Console.WriteLine("p1 = " + p1);
  Console.WriteLine("p2 = " + p2);
  Console.WriteLine("p3 = " + p3);
}
Result:
p1 = C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\root\a897dd66\ec73ff95\assembly\dl3\ff65202d\29daade3_5e84cc01
p2 = C:\inetpub\SBSPortal_staging\
p3 = C:\inetpub\SBSPortal_staging