/// <summary> /// Marks a configuration section for protection. /// </summary> /// <exception cref="T:System.InvalidOperationException"> /// The /// <see cref="P:System.Configuration.SectionInformation.AllowLocation" /> property is set to false. /// </exception> public void ProtectSection() { if (_section == null) { throw new ConfigurationException(); } if (!_section.SectionInformation.IsProtected) { string protectionProvider = _protectionProvider.GetDescription(); SectionInformation sectionInformation = _section.SectionInformation; sectionInformation.ProtectSection(protectionProvider); Save(Resources.ConfigurationSectionHelper_ProtectSection); } }
/// <summary> /// Saves the provided connectionString to the program's configurations file using the default name, and Rsa encryption. /// </summary> /// <param name="connectionString">The connection string to save.</param> public void SaveConnectionString() { if (!ConnectionString.Equals(string.Empty) && !ConnectionString.Equals(DEFAULT_CONSTR)) { ConnectionStringsSection section = _config.ConnectionStrings; SectionInformation sectionInfo = section.SectionInformation; if (!sectionInfo.IsProtected) { sectionInfo.ProtectSection("RsaProtectedConfigurationProvider"); } ConnectionStringSettings existingSection = section.ConnectionStrings[DEFAULT_CONSTR_NAME]; if (null != existingSection) { section.ConnectionStrings.Remove(existingSection); } section.ConnectionStrings.Add(new ConnectionStringSettings(DEFAULT_CONSTR_NAME, _conStrBuilder.ConnectionString)); _config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("connectionStrings"); } }
public static void EncryptAppConfigSections(string exePath, string commaSeparatedSections) { List <string> sectionNames = new List <string>(commaSeparatedSections.Split(",".ToCharArray())); Configuration config = ConfigurationManager.OpenExeConfiguration(exePath); SectionInformation sectionInformation = null; foreach (string sectionName in sectionNames) { sectionInformation = config.GetSection(sectionName.Trim()).SectionInformation; if (sectionInformation == null) { continue; } if (!sectionInformation.IsProtected) { sectionInformation.ProtectSection(configProtectionProvider); sectionInformation.ForceSave = true; } } config.Save(ConfigurationSaveMode.Full); }