Updating app setting automatically using c# code



In this article, we will see how to update app settings or configuration settings using c# code.

There may be requirement where we need to update the settings from code side and moreover it should reflects the changes immediately. 

If no settings exist in the file it should create new pair of settings to file.

Let see how to do so using c# code.

        public bool CreateOrUpdateAppSettings(string key, string value)
        {
            bool config_changed = false;
            try
            {
                var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                var settings = configFile.AppSettings.Settings;
                if (settings[key] == null)
                {
                    settings.Add(key, value);
                }
                else
                {
                    settings[key].Value = value;
                }
                configFile.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
                config_changed = true;
            }
            catch (ConfigurationErrorsException)
            {
                return false;
            }
            return config_changed;
        }

 

Labels: app settings c#, app settings updating using code, config setting update code, configuration settings updating using c#



Subscribe

Receive Quality Tutorials Straight in your Inbox by submitting your Email below:

Delivered by FeedBurner

Protected by Copyscape Duplicate Content Checker