Matthew
Matthew

Reputation: 311

.Net Core 3.0 executable doesn't read appsettings.json

I'm writing a simple .Net Core 3.0 console application and publishing as a single executable.

I figured out how to exclude the appsettings.json file, but when I run the application it uses the original settings and doesn't honor changes I make to the `appsettings.json file.

Perhaps when I run the executable it is copying the original appsettings.json file to a temp folder somewhere and reading that rather than the file at the original location?

If so, where is that temp location when running on Debian Linux?

static void Main(string[] args)
{
    private static MySettings settings = new MySettings();

    var config = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json", false, true)
        .Build();

    config.GetSection("Settings").Bind(settings);

    rootPath = settings.RootPath;
}

public class MySettings
{ 
    public int Buffer { get; set; }
    public string RootPath { get; set; }
    public int FrequencySeconds { get; set; }
}

Upvotes: 8

Views: 4676

Answers (1)

Nkosi
Nkosi

Reputation: 246998

Try setting the base path to the working directory

.SetBasePath(Directory.GetCurrentDirectory())

Also, the binding can be done using .Get<T>() on the section

static void Main(string[] args) {    

    var config = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory()) //<--
        .AddJsonFile("appsettings.json", false, true)
        .Build();

    MySettings settings = config.GetSection("Settings").Get<MySettings>();

    rootPath = settings.RootPath;
}

Upvotes: 6

Related Questions