[SOLVED] Rewriting IConfiguration appsettings.json with Command Line Arguments in C# 10 .NET 6

Issue

This Content is from Stack Overflow. Question asked by Francesco Girelli

I’m making console application in C# 10 .NET 6 using the Dependency Injection.
I have an appsettings.json file that i load by IConfiguration but i have also added a custom IConfigurationSource that loads data in a specific way by the Command Line Arguments.
It works because if i write a CLA that overrides an appsettings.json property then it does.
What I want to do is that if i override a particular appsettings.json property via CLA I want it to update the property inside the appsettings.json file so I don’t have to start the application with the same CLA again and again. How do I accomplish that?

private IConfiguration SetUpConfiguration()
{
    IConfiguration configuration = new ConfigurationBuilder()
    .AddAppSettingsFile()
    .AddCommandLineArgumentBuilder(_args)
    .Build();
    return configuration;
}

I Wrote it in a simplified version to make you see the “structure” of what I wrote.



Solution

You need to derive from JsonConfigurationProvider and override the Set-Method so it actually writes values back to the file.


This Question was asked in StackOverflow by Francesco Girelli and Answered by jeanluc162 It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?