Ranjith Varatharajan
Ranjith Varatharajan

Reputation: 1694

Adding appsettings.json to the publish folder

I have a dotnet core console project where it takes some data from appsettings.json. It works when running directly from command promt i.e dotnet run. But when built, it says appsettings.json is not found on the folder. How to copy the appsettings.json to the build folder?

Here is my console code:

class Program
{
    public static void Main(){
        var builder = new ConfigurationBuilder();
        BuildConfig(builder);

        Log.Logger = new LoggerConfiguration()
            .ReadFrom.Configuration(builder.Build())
            .CreateLogger();

        var host = Host.CreateDefaultBuilder()
            .ConfigureServices((context, services) =>
            {
                services.AddTransient<ICoviSlotTrackerService, CoviSlotTrackerService>();
            })
            .UseSerilog()
            .Build();

        var svc = ActivatorUtilities.CreateInstance<CoviSlotTrackerService>(host.Services);
        svc.Run();
    }

    static void BuildConfig(IConfigurationBuilder builder)
    {
        builder.SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) // adding the json file here
            .AddEnvironmentVariables();
    }

}

Here is how the folder structure is

enter image description here

When I run dotnet build and double-click exe, i get this error

enter image description here

Upvotes: 0

Views: 883

Answers (1)

mexanichp
mexanichp

Reputation: 433

You can specify the following XML in your .csproj file:

<Content Include="appsettings.json">
    <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>

This way you're telling the MSBuild process that it should copy the content file.

Upvotes: 2

Related Questions