Encrypt connectionstrings in app.config


/ Published in: C#
Save to your folder(s)



Copy this code and paste it in your HTML
  1. public static class EncryptConnection
  2. {
  3. public static void EncryptConnectionString(bool encrypt)
  4. {
  5. Configuration configFile = null;
  6. try
  7. {
  8. // Open the configuration file and retrieve the connectionStrings section.
  9. configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
  10. ConnectionStringsSection configSection = configFile.GetSection("connectionStrings") as ConnectionStringsSection;
  11.  
  12. if ((!(configSection.ElementInformation.IsLocked)) && (!(configSection.SectionInformation.IsLocked)))
  13. {
  14. if (encrypt && !configSection.SectionInformation.IsProtected)//encrypt is false to unencrypt
  15. {
  16. configSection.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
  17. }
  18.  
  19. if (!encrypt && configSection.SectionInformation.IsProtected)//encrypt is true so encrypt
  20. {
  21. configSection.SectionInformation.UnprotectSection();
  22. }
  23.  
  24. //re-save the configuration file section
  25. configSection.SectionInformation.ForceSave = true;
  26.  
  27. // Save the current configuration.
  28. configFile.Save();
  29. }
  30. }
  31. catch (System.Exception ex)
  32. {
  33. throw (ex);
  34. }
  35. finally
  36. {
  37. }
  38. }
  39. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.