C# creating Web.config file programmatically

这一生的挚爱 提交于 2020-01-06 04:05:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!