© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•4y ago•
82 replies
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);
            
        }
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);
            
        }
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements
Next page

Similar Threads

Overriding appsettings.json section with environment variable
C#CC# / help
14mo ago
❔ Check if appsettings.json or appsettings.Development.json
C#CC# / help
3y ago
Appsettings.json across projet
C#CC# / help
2y ago
✅ serilog and appsettings.json unable to build configuration
C#CC# / help
3y ago