本文實(shí)例講述了C#加密app.config中連接字符串的方法。分享給大家供大家參考。具體如下:
連接字符串中包含數(shù)據(jù)庫的訪問信息,帳號(hào)和密碼,因此一般不以明文顯示,本代碼用來加密連接字符串。
public static class EncryptConnection{  public static void EncryptConnectionString(bool encrypt)  {   Configuration configFile = null;   try   {    // Open the configuration file and retrieve the connectionStrings section.    configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);    ConnectionStringsSection configSection = configFile.GetSection("connectionStrings") as ConnectionStringsSection;    if ((!(configSection.ElementInformation.IsLocked)) && (!(configSection.SectionInformation.IsLocked)))    {     if (encrypt && !configSection.SectionInformation.IsProtected)     //encrypt is false to unencrypt     {      configSection.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");     }     if (!encrypt && configSection.SectionInformation.IsProtected)     //encrypt is true so encrypt     {      configSection.SectionInformation.UnprotectSection();     }     //re-save the configuration file section     configSection.SectionInformation.ForceSave = true;     // Save the current configuration.     configFile.Save();    }       }   catch (System.Exception ex)   {    throw (ex);   }   finally   {   }  }}希望本文所述對(duì)大家的C#程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選