How to obtain Content and Web roots paths in ASP.NET Core RC2

By Dawid on (tags: core, .net, path, rc2, root, categories: code)

There are many situations that developer needs to known what are the content or web roots paths. One of such situations is accessing custom JSON configuration files. In the classics ASP.NET applications you was always able to use Server.MapPath() method. With that method you was able to find physical path or web root directory. Later on in RC1 there was possibility to use IApplicationEnvironment service.

That’s not possible in ASP.NET Core. Those paths (web root and content root) are accessible in IHostingEnvironment service which can be simply injected in almost any place of code. Here is an example usage of that service:

   1: public class JsonStringLocalizerFactory: IStringLocalizerFactory
   2: {
   3:     private readonly IHostingEnvironment _hostingEnvironment;
   4:  
   5:     public JsonStringLocalizerFactory(IHostingEnvironment hostingEnvironment)
   6:     {
   7:         _hostingEnvironment = hostingEnvironment;
   8:     }
   9:  
  10:     public IStringLocalizer Create(Type resourceSource)
  11:     {
  12:         string resourceTypeName = resourceSource.Name;
  13:         string contentPath = _hostingEnvironment.ContentRootPath
  14:         ...
  15:     }
  16:  
  17:     ...
  18: }

For more information’s take look in the documentation or source code.