Friday 5 June 2015

Application current folder in C#

There are various predefined functions are available in 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
string path1 = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
string path2 = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
string path3 = this.Server.MapPath("");
//path1 = C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\root\a897dd66\ec73ff95\assembly\34543543 - 435 - 345 - 35345 - 435 - 435
//path2 = C:\inetpub\
//path3 = C:\inetpub\

How to get Application Path in Core?
IHostingEnvironment of Microsoft.AspNetCore.Hosting play big role in getting application path and all application related information in dotnet core. HttpContext.Server is not available under core. 
using System.Collections.Generic;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
namespace AngCore.Api.Controllers
    public class ValuesController : ControllerBase
        IHostingEnvironment _hostingEnvironment;
        public ValuesController(IHostingEnvironment hostingEnvironment)
            _hostingEnvironment = hostingEnvironment;
        // GET api/values
        // public ActionResult<IEnumerable<string>> Get()
        public ActionResult<IEnumerable<string>> Get()
            string applicationPath = _hostingEnvironment.ContentRootPath;
            string wwwrootPath = _hostingEnvironment.WebRootPath;
            return new string[] { applicationPathwwwrootPath };