Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Directory.GetCurrentDirectory() doesn't return the correct directory [duplicate]

In my ASP.NET Core 2.2 MVC server, I want to add a folder to store static files. I found the following code to perform that:

app.UseStaticFiles(new StaticFileOptions {
    FileProvider = new PhysicalFileProvider(
        Path.Combine(Directory.GetCurrentDirectory(), "StaticFiles")),
    RequestPath = "/StaticFiles"
});

In my computer, the project is located in "C:\Users\MyUsername\source\repos\WebApplication1\WebApplication1", in the same directory there is a folder called "StaticFiles" and a Startup.cs file where the code above is written.

But when I execute the code I got the following error:

'System.IO.DirectoryNotFoundException' in Microsoft.Extensions.FileProviders.Physical.dll C:\Program Files\IIS Express\StaticFiles\

The Directory.GetCurrentDirectory() is returning "C:\\Program Files\\IIS Express" instead of "C:\Users\MyUsername\source\repos\WebApplication1\WebApplication1". How can I get the correct direction?

like image 324
Ender Look Avatar asked Feb 03 '19 23:02

Ender Look


1 Answers

The IHostingEnvironment interface provides information about the environment including the base path. You can get an instance using dependency injection.

public class Startup
{
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        // env.ContentRootPath;
    }
}
like image 125
Jonas Tuemand Møller Avatar answered Nov 09 '22 23:11

Jonas Tuemand Møller