Home > Software engineering >  Unable To Add Value To Custom App.Config Section
Unable To Add Value To Custom App.Config Section

Time:12-16

I am absolutely at my wits end with this, having tried basically everything. I also do not see any existing stackoverflow threads about doing this.

I have an app.config file for my C# project, and it stores a list of servers which the user can create and add to.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <configSections>
        <section name="servers" type="System.Configuration.AppSettingsSection" />
    </configSections>
    <servers>
        <add key="server" value="678,true,true"/>
    </servers>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8"/>
    </startup>
    <appSettings>
        <add key="nightmode" value="Dark"/>
        <add key="theme" value="Red"/>
    </appSettings>
    <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
            <dependentAssembly>
                <assemblyIdentity name="ControlzEx" publicKeyToken="69f1c32f803d307e" culture="neutral"/>
                <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0"/>
            </dependentAssembly>
        </assemblyBinding>
    </runtime>
</configuration>

((NameValueCollection)ConfigurationManager.GetSection("servers")).Add("server", $"{port},"   $"{ (dialogResult1 == MessageDialogResult.Affirmative) },{dialogResult2 == MessageDialogResult.Affirmative}");

When the user goes to add a new key the the "servers" section, it throws the below exception.

System.Configuration.ConfigurationErrorsException: 'The configuration is read only.'

I am bewildered why this is happening

CodePudding user response:

I ended up generating my own XML configuration, since that appears to be the best way to do things.

CodePudding user response:

you can try:

Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

config.AppSettings.Settings.Add("test", "propertyValue");

config.Save(ConfigurationSaveMode.Modified, true);
            System.Configuration.ConfigurationManager.RefreshSection("appSettings");

string test = ConfigurationManager.AppSettings["test"];

This get de appsettings section values.

Ps.: You need Install-Package System.Configuration.ConfigurationManager.

  • Related