/// <summary> /// Saves or updates in the configuration (in appSettings) the key and value passed. /// </summary> /// <param name="key">Key to use to save the value</param> /// <param name="value">Value to be saved (it will be trimmed)</param> /// <param name="encript">True if the value must be encrypted, false otherwise</param> public static void SetKey(string key, string value, bool encript = false) { //Open the configuration System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); try { //Encrypt the value if needed string strValue = value; if (encript) { using (CryptoUtilities crypto = new CryptoUtilities()) { strValue = crypto.EncryptToString(value); } } //Add the key-value in the configuration config.AppSettings.Settings.Remove(key); config.Save(ConfigurationSaveMode.Modified); config.AppSettings.Settings.Add(key, strValue.Trim()); config.Save(ConfigurationSaveMode.Modified); //Refresh the configuration to take the new key-value ConfigurationManager.RefreshSection("appSettings"); } catch (Exception ex) { throw new SystemConfigurationException(ex, "The key {0} could not be saved in the configuration", key); } }