Locked Configuration manager help

  • Friday, October 17, 2008 2:56 PM
     
     

    I have what is probably a very stupid question, but I'm just starting to try to teach myself C# so please be gentle.

     

    I'm trying to figure out how to update my app.config file in code.  I've set up one button to display a value from my app.config, and a 2nd to update it based on the value of a text box.  When I execute the code in my 2nd button, the first one always displays the same value and I'm trying to figure out what I'm doing wrong.  Can anyone help?  The code I'm trying to use the update the setting is below:

     

    // Get the configuration file.

    System.Configuration.Configuration config =

    ConfigurationManager.OpenExeConfiguration(

    ConfigurationUserLevel.None);

     

    ConfigurationManager.AppSettings["test1"] = valueBox.Text;

     

     

    // Save the configuration file.

    config.Save(ConfigurationSaveMode.Modified);

     

    // Force a reload of the changed section.

    ConfigurationManager.RefreshSection("appSettings");

     

    I can get it to work when I replace the "ConfigurationManager.AppSettings["test1"] = valueBox.Text;" line with :

    config.AppSettings.Settings.Remove("test1");

    config.AppSettings.Settings.Add("test1", valueBox.Text);

     

    Is that the way to go?

All Replies

  • Tuesday, October 21, 2008 6:03 AM
    Moderator
     
     Answered

    Hello,

            If you want to modify the value of configuration file in the run time, I guess we could do as you have mentioned, remove and add.   The reason is showed here:  Property or indexer 'System.Configuration.KeyValueConfigurationCollection.this[string]' cannot be assigned to -- it is read only”.

            Or maybe you want to modify the app.config file and then save it, not just modify the value of run time configuration settings, following codes are helpful.   And please remember that the effect will take effect the next time when run the application.  

    Code Snippet

    XmlDocument xmlDoc = new XmlDocument();

    xmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

     

    foreach (XmlElement element in xmlDoc.DocumentElement)

    {

        if (element.Name.Equals("appSettings"))

        {

             foreach (XmlNode node in element.ChildNodes)

             {

                 if (node.Attributes[0].Value.Equals("Setting1"))

                 {

                     node.Attributes[1].Value = "New Value";

                 }

             }

        }

    }

     

    xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

     

     

            Thanks,

    Best Regards,
    Lingzhi