Posted By

lance on 02/04/11


Tagged

encrypt connectionstrings


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

ovuncgursoy


Encrypt connectionstrings in app.config


 / Published in: C#
 

  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  

You need to login to post a comment.