Introducing Radical.sh

Forget Code launches a powerful code generator for building API's

Connection string management in C#

Connection is the important and primary object in .NET technology.

Many times users will feel the difficulty of making connection between two applications.
You can render any kind of queries and codes to achieve the target but only after making the connection. Isn't it?

Here two approaches are given to connect to any database using C# in .NET application.


APPROACH 1 (Standard)

STEP 1: Save the connection string in App.config file
STEP 2: Use the saved connection string in program


1: Saving in Connection strings section in App.Config file
  1. <configuration>
  2. <connectionStrings>
  3. <add name="MyConnectionString" connectionString="Data Source=(local);Initial Catalog=DatabaseName; Persist Security Info=True;UserID=Name Password=MyPwd;Connect providerName="System.Data.SqlClient"/>
  4. </connectionStrings>
  5. </configuration>


[Program code : C#]
2: Fetching connection string from ConfigurationManager: (Standard way)
  1. string MyconnString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;





APPROACH 2 (Advanced) (Saving programmatically)
(No need to touch web/App config files)

[Program code : C#]

[Saving in ConfigurationManager programatically]

  1. Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
  2. config.ConnectionStrings.ConnectionStrings.Clear();
  3.  
  4. //For saving the connection string in Configuration file
  5. string con = "DSN=MyDataBase;Uid=User1;Pwd=*****;";
  6.  
  7.  
  8. config.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings("NewConnection", con));
  9. config.Save();
  10.  
  11. ConfigurationManager.RefreshSection(config.ConnectionStrings.SectionInformation.SectionName);
  12.  
  13.  
  14. //[Using the stored connection string in our program]
  15. //[ODBC connection has been used here for example. We can use our own drivers]
  16.  
  17.  
  18. OdbcConnection OdbcCon;
  19. ConnectionStringSettings connection = ConfigurationManager.ConnectionStrings["NewConnection"];
  20.  
  21. if ((connection!= null) && (connection.ConnectionString != null))
  22. {
  23. string MyConnection = connection.ConnectionString;
  24. }
  25.  
  26. OdbcCon = new OdbcConnection(MyConnection);
  27.  
  28.  
  29. // If you want to remove a particular connection in config file,
  30. //you can use the below code before adding a new one to config file
  31. config.ConnectionStrings.ConnectionStrings.Remove("NewConnection");
  32. config.ConnectionStrings.ConnectionStrings.Clear();
  33.  


Once you stored the connection string in config file either by programatically or by updating app.config, you can retrieve the parameters (UserID,Password) using the below ways also:

  1. // [Retrieve using ConnectionStringBuilder]
  2.  
  3. SqlConnectionStringBuilder con = new SqlConnectionStringBuilder(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
  4. string userID = con.UserID;
  5. string password = con.Password;
  6.  
  7. // [Retrieve using var type]
  8.  
  9. var builder = new SqlConnectionStringBuilder(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString)
  10. var userID = builder.UserID;
  11. var password = builder.Password;
  12.  
  13. //[Retrieve using split operator]
  14.  
  15. var connectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
  16. var splitters = connectionString.Split(';');
  17.  
  18. string userId;
  19. string password;
  20.  
  21. for(var i = 0; i < splitters.Length; i++) {
  22. var splittedSection = splitters[i];
  23. if(splittedSection.StartsWith("User ID"))
  24. userId = splittedSection.Substring(splittedSection.IndexOf("=") + 1);
  25.  
  26. if(splittedSection.StartsWith("Password"))
  27. password = splittedSection.Substring(splittedSection.IndexOf("=") + 1);
  28. }
  29.