Search This Blog

Sunday, January 24, 2021

Update App Config During Runtime In C#

NameValueCollection sAll = ConfigurationManager.AppSettings;

            foreach (string str in sAll.AllKeys)

            {

                if (str == appkey)

                {

                    label2.Text = sAll.Get(str);

                }

            } 


// Get AppSettings section from the Config

            Configuration config = ConfigurationManager.OpenExeConfiguration(this.GetType().Assembly.Location);

            AppSettingsSection App_Section = (AppSettingsSection)config.GetSection("appSettings");

            KeyValueConfigurationCollection app_settings = App_Section.Settings;

            KeyValueConfigurationElement element = app_settings[appkey];

            // Grab Key-Value pair & Make your Change

            if (element != null)

            {

                //Create the object

                if (element.Value != label2.Text)

                {

                    element.Value = label2.Text;

                    app_settings.Remove(appkey);

                    app_settings.Add(element);

                    //save to apply changes

                    config.Save();

                    ConfigurationManager.RefreshSection("appSettings");

                    MessageBox.Show("Succeefully changed the Link.\nPlease exit Application and reopen to change reflection..!");                  

                    this.Close();                   

                }   

            }

            else

            {

                MessageBox.Show("Setting not Modified");

            }


No comments:

Post a Comment