C#C
C#3y ago
kaziux

✅ How to edit and save specific appsettings.json (project root) section?

Hello, I have issue with editing specific section in the appsettings.json in project root folder, but now it overwrites all he file although it should overwrite only the specific section
public void SetYear(int year)
        {
            var config = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddEnvironmentVariables()
                .Build()
                .Get<Config>();

            config.ConfigurableYear = year;

            var jsonWriteOptions = new JsonSerializerOptions()
            {
                WriteIndented = true,
                
            };

            var newJson = JsonSerializer.Serialize(config, jsonWriteOptions);

            var appSettingsPath = Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json");
            File.WriteAllText(appSettingsPath, newJson);
            
        }
Was this page helpful?