Search code examples
c#configurationmanager

C# ConfigurationManager does not save changes


I have a custom Configuration manager class which gets and sets key and value into a config file. I can get the the values in the config file but the problem is saving it does not save changes of the values to the config file.

Here is my custom class

public class CsvManagerConfiguration
{
    private readonly Configuration config;

    public CsvManagerConfiguration()
    {
        string configFile = AppDomain.CurrentDomain.BaseDirectory + @"\CsvManager.config";
        AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", configFile);

        config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    }

    public string GetValue(string name)
    {
        //return ConfigurationManager.AppSettings[name];
        return config.AppSettings.Settings[name].Value;
    }

    public void SetValue(string name, string value)
    {
        //ConfigurationManager.AppSettings[name] = value;
        config.AppSettings.Settings[name].Value = value;
        config.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection("appSettings");
    }
}

and config file content

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="Format" value="StoresFixedPrice"/>
    <add key="Duration" value="GTC"/>
    <add key="AcceptPaypal" value=""/>
    <add key="PaypalEmail" value=""/>
    <add key="Location" value="10969"/>
    <add key="DispatchTimeMax" value="3"/>
    <add key="ReturnsAcceptedOption" value="ReturnsAccepted"/>
    <add key="InputFileDelimiter" value="tab"/>
    <add key="HtmlTemplateFilePath" value="template.html"/>
  </appSettings>
</configuration>

Solution

  • your code looks correct - but make sure you are looking at the right file. Inspect config.FilePath in debugger to see what file you are changing.

    most likely you run your app from VS - and expect it to update your project root\app.config file - but the file you are updating is project root\bin\debug\app.config