這篇文章主要介紹了C#加密app.config中連接字符串的方法,涉及C#配置文件加密的相關(guān)實(shí)現(xiàn)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下
本文實(shí)例講述了C#加密app.config中連接字符串的方法。分享給大家供大家參考。具體如下:
連接字符串中包含數(shù)據(jù)庫(kù)的訪(fǎng)問(wèn)信息,帳號(hào)和密碼,因此一般不以明文顯示,本代碼用來(lái)加密連接字符串。
- 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)
疑難解答
圖片精選
網(wǎng)友關(guān)注