locked
Update appSetting values for specific keys RRS feed

  • Question

  • User-1392375537 posted

    Hi All,

    I've a requirement to update specific key values on <appSettings> node as shown below (i.e) for keys test1, test4, test7 and test9 the values should change. Have code to change the value for a specific node. But, need source code for to change for specific keys. Can anyone help on this.

      <appSettings>
        <add key="test1" value="One" />
        .....
        .....
        <add key="test4" value="Four" />
        <add key="test7" value="Seven" />
        <add key="test9" value="Nine" />
        .....
      </appSettings>


    Code:

    XmlDocument doc = new XmlDocument();
    doc.Load(path);
                               
    XmlNodeList nlist = doc.DocumentElement.SelectNodes(string.Format("appSettings/add[@key='{0}']", "test1"));
    XmlNode node;

    node = nlist[0];
    if (node != null)
    {                                       
            node.Attributes["value"].Value = "myOne";
            doc.Save(path);
    }

    Output:

      <appSettings>
        <add key="test1" value="myOne" />
      </appSettings>

    Thanks,

    Anand

    Wednesday, November 22, 2017 6:54 PM

Answers

  • User2103319870 posted

    kka_anand

    But, need source code for to change for specific keys.

    You can use the below code 

     public void AddUpdateAppSettings(string key, string value)
            {
                try
                {
                    //Load your file path here
                    string path = "Your config file path here";
                    ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
                    configFileMap.ExeConfigFilename = path;
                    System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
                    //Get the appsettings value
                    var settings = config.AppSettings.Settings;
                    //check if input key is new or already existing
                    if (settings[key] == null)
                    {
                        //if new then add the value
                        settings.Add(key, value);
                    }
                    else
                    {
                        //if not then update the key value
                        settings[key].Value = value;
                    }
                    config.Save(ConfigurationSaveMode.Modified);
                    ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name);
                }
                catch (ConfigurationErrorsException exs)
                {
                    throw new Exception("Error writing app settings" + exs.InnerException);
                }
            }

    Call above method like below, where first parameter is the key name and second parameter is actual value

    AddUpdateAppSettings("test1", "myOne");
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, November 22, 2017 7:23 PM

All replies

  • User2103319870 posted

    kka_anand

    But, need source code for to change for specific keys.

    You can use the below code 

     public void AddUpdateAppSettings(string key, string value)
            {
                try
                {
                    //Load your file path here
                    string path = "Your config file path here";
                    ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
                    configFileMap.ExeConfigFilename = path;
                    System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
                    //Get the appsettings value
                    var settings = config.AppSettings.Settings;
                    //check if input key is new or already existing
                    if (settings[key] == null)
                    {
                        //if new then add the value
                        settings.Add(key, value);
                    }
                    else
                    {
                        //if not then update the key value
                        settings[key].Value = value;
                    }
                    config.Save(ConfigurationSaveMode.Modified);
                    ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name);
                }
                catch (ConfigurationErrorsException exs)
                {
                    throw new Exception("Error writing app settings" + exs.InnerException);
                }
            }

    Call above method like below, where first parameter is the key name and second parameter is actual value

    AddUpdateAppSettings("test1", "myOne");
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, November 22, 2017 7:23 PM
  • User-1392375537 posted

    Thanks A2H. It works fine.

    Regards,

    Anand

    Wednesday, November 22, 2017 7:58 PM
  • User-1392375537 posted

    A2H,

    I call the function at different events (button click) on the same page. On the first button click it works fine. when the same function call at another button click, it throws below error message.

    Line:          config.Save(ConfigurationSaveMode.Modified);

    Error:

    Exception thrown: 'System.Configuration.ConfigurationErrorsException' in System.Configuration.dll

    Additional information: The configuration file has been changed by another program.

    Thanks,

    Anand

    Tuesday, November 28, 2017 2:44 PM
  • User475983607 posted

    There is no good reason to change the web.config from a web app.  For starters updating the web.config causes the web app to restart and that's generally bad for a production application.

    Please explain the problem you are trying to solve.

    Tuesday, November 28, 2017 3:10 PM
  • User-1392375537 posted

    We have multiple projects in a solution and each project config file has many credentials and directories to update. Want to change the data in all projects config files. The method shared by A2H works fine when I execute it first time when I do the same action again it throws error.

    Thanks

    Tuesday, November 28, 2017 5:18 PM
  • User2103319870 posted

    many credentials and directories to update. Want to change the data in all projects config files

    If the fields will get updated regularly then keeping the values in config file is not a good option IMHO. You might consider using database to save the values and then fetch in back while using in your code

    Tuesday, November 28, 2017 5:46 PM
  • User-1392375537 posted

    Thanks for the opinion.

    What's the solution and how to handle the error when the function called second time.

    Thanks,

    Anand

    Tuesday, November 28, 2017 6:04 PM
  • User475983607 posted

    kka_anand

    The method shared by A2H works fine when I execute it first time when I do the same action again it throws error.

    Use a using statement to properly dispose the System.Configuration.Configuration object.  However, you should consider crafting a data driven design.

    using (System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None))
    {
      //do the update
    }
    Tuesday, November 28, 2017 6:10 PM