Store a Database Connection String Securely - CSharp Database

CSharp examples for Database:Connection

Description

Store a Database Connection String Securely

Demo Code


using System;//from  w  w  w  .  jav a2 s  .  com
using System.Configuration;
using System.Data.SqlClient;

class MainClass
    {
        private static void WriteEncryptedConnectionStringSection(
            string name, string constring, string provider)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            ConnectionStringsSection section = config.ConnectionStrings;
            if (section == null)
            {
                Console.WriteLine("Section needs creating");
                section = new ConnectionStringsSection();
                config.Sections.Add("connectionSettings", section);
            }
            if (!section.SectionInformation.IsProtected)
            {
                section.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");
            }
            ConnectionStringSettings cs = new ConnectionStringSettings(name, constring, provider);
            section.ConnectionStrings.Add(cs);
            section.SectionInformation.ForceSave = true;
            config.Save(ConfigurationSaveMode.Full);
        }

        public static void Main(string[] args)
        {
            string conName = "ConnectionString1";
            string conString = @"Data Source=.\sqlexpress;" +
                "Database=Northwind;Integrated Security=SSPI;" +
                "Min Pool Size=5;Max Pool Size=15;Connection Reset=True;" +
                "Connection Lifetime=600;";
            string providerName = "System.Data.SqlClient";

            WriteEncryptedConnectionStringSection(conName, conString, providerName);

            ConnectionStringSettings cs2 = ConfigurationManager.ConnectionStrings["ConnectionString1"];

            using (SqlConnection con = new SqlConnection(cs2.ConnectionString))
            {

            }
        }
    }

Related Tutorials