Shiloh
Shiloh

Reputation: 1878

.net core 3.1 Console App The configuration file 'appsettings.json' was not found

When running a console app outside of a local environment, .net core 3.1 is looking for the appsettings.json file in a different directory than where the program executes.

In previous versions of dotnet using the Environment.CurrentDirectory or Directory.GetCurrentDirectory() but not working in 3.1. How do you change this so that it looks in the directory where it is running? The below does not work

        using var host = Host.CreateDefaultBuilder()
            .ConfigureHostConfiguration(builder =>
            {
                builder.SetBasePath(Environment.CurrentDirectory);                    
                builder.AddCommandLine(args);
            })
            .UseConsoleLifetime(options => options.SuppressStatusMessages = true)
            .UseServiceProviderFactory(new AutofacServiceProviderFactory())
            .ConfigureAppConfiguration((hostContext, builder) =>
            {
                builder.AddJsonFile("appsettings.json");
                hostContext.HostingEnvironment.EnvironmentName = Environment.GetEnvironmentVariable("NETCORE_ENVIRONMENT");
                if (hostContext.HostingEnvironment.EnvironmentName == Environments.Development)
                {
                    builder.AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", optional: true);
                    builder.AddUserSecrets<Program>();
                }
            })

Upvotes: 5

Views: 8408

Answers (3)

Just add useStaticfiles() on your builder method; it will resolve your problem:

app.useStaticfiles() 

Upvotes: 1

Maxim Zabolotskikh
Maxim Zabolotskikh

Reputation: 3367

We add appsettings like this:

public Startup(IWebHostEnvironment env)
        {    
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
...
}

Upvotes: 1

Shiloh
Shiloh

Reputation: 1878

This seems to work, by getting the base directory from AppDomain.CurrentDomain before setting the base path. I still do not understand why this was not required in previous dotnet versions and I was unable to find any MS documentation on this.

Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);

        using var host = Host.CreateDefaultBuilder()
            .ConfigureHostConfiguration(builder =>
            {
                builder.SetBasePath(Directory.GetCurrentDirectory());                    
                builder.AddCommandLine(args);
            })

Upvotes: 6

Related Questions