加密ConnectionString返回未将对象引用设置为实例

时间:2014-10-21 07:15:12

标签: c# .net encryption connection-string

我正在使用vs 2012(4.5)我使用加密来加密我的ConnectionString,但当我打电话给

  connStr = ConfigurationManager.ConnectionStrings["SnOracle"].ConnectionString;

我收到此错误object is not set to an instance of an object

我获取了没有ConnectionStringsSection的MyApp.exe.Config文件的路径 ,但加密MyApp.exe.Config.config DO有ConnectionStringsSection.Meybe我需要设置路径到 我自己或AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;的MyApp.exe.Config.config需要返回加密文件的路径吗?

如何从Encrypted MyApp.exe.Config.config文件中读取ConnectionStringsSection?

我做错了什么?

我的代码:

    string path = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
// This return path to-> MyApp.exe.Config   file that dont have  ConnectionStringsSection
//But Encrypted  MyApp.exe.Config.config DO have  ConnectionStringsSection
  Configuration config = ConfigurationManager.OpenExeConfiguration(path);
        ConnectionStringsSection section = config.GetSection("connectionStrings") as ConnectionStringsSection;

                if (!section.SectionInformation.IsProtected)
                {
                    // Encrypt the section.
                    section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");

                }
                step = "9";
                // Remove encryption.
                // section.SectionInformation.UnprotectSection();
                // Save the current configuration.

                config.Save();
                step = "9a";
                string connStr = "";
                try
                {
                     //here i getting the error
                    connStr = ConfigurationManager.ConnectionStrings["SnOracle"].ConnectionString;

                }
                catch (Exception ex)
                {
                    //here afert it fails i insert it hard coded
                    connStr = "Data Source=xxx;User Id=xxx;Password=xxx";

                }

MyApp.exe.Config:

<?xml version="1.0"?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
  </startup>
  <appSettings>

  </appSettings>
</configuration>

MyApp.exe.Config.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <connectionStrings configProtectionProvider="DataProtectionConfigurationProvider">
        <EncryptedData>
            <CipherData>
                <CipherValue>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAffcYl/Mg5kKs24jULobCqAQAAAACAAAAAAADZgAAwAAAABAAAADYu948udrIvfvh5iP1Atz/AAAAAASAAACgfgLks14VfblBt3TX0E5ZnkwAAAASK+Jz3H9lx7DWVEQGXVS2HhqURpMbgFenk6v/lO6lMOk7Gv+tEhEmLs/zNApOaYNFAAAAJ1UfmT1bhg4zzVFv9/RcjNKjRzL</CipherValue>
            </CipherData>
        </EncryptedData>
    </connectionStrings>
</configuration>

0 个答案:

没有答案