BlackSpy
BlackSpy

Reputation: 5603

ASP.NET Core 3.1 WebRoot Path

I am pushing an external file into the wwwroot folder of my ASP.NET Core 3.1 application. I need to reference the path to provide a constructor variable during the services wire up.

In the Startup class I have added the IWebHostEnvironment to the constructor parameters:

public Startup(IConfiguration configuration, IWebHostEnvironment env)
{
  Configuration = configuration;
  _env = env;
}

When debugging, it seems that _env.WebRootPath returns the path as it is in my source folder, rather than the path being executed, i.e.

It returns: <path to my source code>/wwwroot

Instead of the execution relative path: <path to my source code>/bin/Debug/netcoreapp3.0/wwwroot

How do i get it to return the correct, execution relative path?

Upvotes: 4

Views: 16666

Answers (4)

Nur.B
Nur.B

Reputation: 397

private readonly IWebHostEnvironment _env;

public HomeController(IWebHostEnvironment env)
{
   _env = env;
}

public ActionResult Index()
{
   string contentRootPath = _env.ContentRootPath;
   string webRootPath = _env.WebRootPath;
   return Content(contentRootPath + "\n" + webRootPath);
}

Upvotes: 3

mesutpiskin
mesutpiskin

Reputation: 1937

It worked for me

string applicationPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

Upvotes: 1

alsami
alsami

Reputation: 9835

It's because by default the content-root path is the directory where the project is located rather than its output.

If you want to change that behavior, you have to call this line when building the web-host.

.UseContentRoot(AppContext.BaseDirectory);

Then the path will change to <ProjectPath>\Debug\netcoreapp3.1 or whatever you are compiling to.

Upvotes: 3

vasilisdmr
vasilisdmr

Reputation: 609

Maybe try something like the following:

var rootDir  = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;

For further information/help take a glance on this article: Getting the Root Directory Path for .Net Core Applications

Upvotes: 4

Related Questions