问题
I'm writing and installer for an ASP.NET application, and I have a few data fields, (connection strings, smtp servers, etc), that I want the installer to build from user input, encrypt and store in the Web.config file. The issue I am having is that both WebConfigurationManager and ConfigurationManager are both designed to work off existing configuration files. How can I construct a new configuration file, and encrypt it before saving it?
回答1:
I would recommend starting with a base configuration file that does not contain fields you want, then using XDocument
or WebConfigurationManger
add the configuration information and encrypt it.
Source: Encrypting and decrypting sensitive data in your web.config files using Protected configuration - Part IV
Code incase the content goes down:
private void EncryptConfig()
{
// Open the Web.config file.
Configuration config =
WebConfigurationManager.OpenWebConfiguration("~");
// Get the connectionStrings section.
ConnectionStringsSection section =
config.GetSection("connectionStrings") as ConnectionStringsSection;
// Toggle encryption.
if (section.SectionInformation.IsProtected)
{
section.SectionInformation.UnprotectSection();
}
else
{
if (!section.SectionInformation.IsLocked)
{
section.SectionInformation
.ProtectSection("RsaProtectedConfigurationProvider");
section.SectionInformation.ForceSave = true;
//Save changes to the Web.config file.
config.Save(ConfigurationSaveMode.Full); }
}
}
来源:https://stackoverflow.com/questions/8813144/c-sharp-creating-web-config-file-programmatically