本文實例講述了C#加密app.config中連接字符串的方法。分享給大家供大家參考。具體如下:
連接字符串中包含數據庫的訪問信息,帳號和密碼,因此一般不以明文顯示,本代碼用來加密連接字符串。
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 { } }}
希望本文所述對大家的C#程序設計有所幫助。
新聞熱點
疑難解答