7

How to update app settings key, value dynamically on app.config file in c# winforms. Key,value are listed below

<appSettings>
    <add key="logPath" value="C:\EventLogs" />
    <add key="isScreenCaptureMode" value="false" />
    <add key="isStartOnSysStartUp" value="false" />
</appSettings>
vijesh
  • 1,115
  • 1
  • 11
  • 27

2 Answers2

12
Configuration configuration = ConfigurationManager.
OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
configuration.AppSettings.Settings["logPath"].Value = DateTime.Now.ToString("yyyy-MM-dd");
configuration.Save();
ConfigurationManager.RefreshSection("appSettings");
vijesh
  • 1,115
  • 1
  • 11
  • 27
2

I believe this is what you are looking for:

using System.Configuration;

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                config.AppSettings.Settings["isScreenCaptureMode"].Value = "true";
                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("appSettings");
Sabri
  • 189
  • 1
  • 1
  • 13
  • @Sabari I did the same. But the updated value is not reflecting in app.config file. – vijesh Mar 27 '18 at 11:53
  • @vijesh Note that if you are running/debugging the application from Visual Studio, this will not update the App.Config file. Go to the bin/Debug folder, launch the application from there. Then the values will be updated in the YourApplication.exe XML Configuration file. You can open that file with notepad to view the change. – Sabri Mar 27 '18 at 12:03
  • @Sabari, I have tried it, but changes were not updating in the file – vijesh Mar 27 '18 at 12:12
  • I have created this test application for you with the same code I posted above. It is performing the functionality you are asking about.https://quickfileshare.org/6r3/Debug.rar – Sabri Mar 27 '18 at 12:23
  • Put anything in the textbox, press update. Close the app and then check the WindowsFormsApplication6.exe.config file in notepad. Your value will be there. – Sabri Mar 27 '18 at 12:28
  • Changing the first line to Configuration configuration = ConfigurationManager. OpenExeConfiguration(Assembly.GetExecutingAssembly().Location); . Its is working. I will update the answer. Thanks for your support bro – vijesh Mar 27 '18 at 12:36