I already have a connection string in my config file
<connectionStrings>
<add
name="ConnectionString"
connectionString="Data Source=*;Initial Catalog=*;User ID=*;Password=*"
providerName=".NET Framework Data Provider for SQL Server" />
Currently I am just adding another connection string in my .cs file:
SqlConnection myConnection =
new SqlConnection("user id=*;password=*;server=localhost;");
I want to use config file string to connect to a database in the .cs file without adding another string. How can I do that?
using (SqlConnection cn =
new SqlConnection(
ConfigurationManager.ConnectionStrings["MyDbConn"].ToString()))
This was the code I found, is there any shorter way?
Just use System.Configuration.ConfigurationManager.ConnectionStrings to get access to the connection string defined in your config file.
You can create a static helper class, named Config or something similar and give it a property ConnectionString, that will return the long "WebConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString" thing. That is the approach I usually go with in my projects and it's actually very easy to use.
This approach is the most useful when more classes need to acccess the connection string and this way you have a centralized access to it and easy to change solution.
Using
ConnectionStrings
property of System.Web.Configuration.WebConfigurationManager to get connection string in config fileNot really, but you could wrap it in its own little helper function: