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?
Not really, but you could wrap it in its own little helper function:
private static string GetConnectionString(string name)
{
return WebConfigurationManager.ConnectionStrings[name].ConnectionString;
}
using (var cn = new SqlConnection(GetConnectionString("MyDbConn"))) { ... }
Using ConnectionStrings
property of System.Web.Configuration.WebConfigurationManager to get connection string in config file
Just use System.Configuration.ConfigurationManager.ConnectionStrings to get access to the connection string defined in your config file.
var myconnectionString = System.Configuration.ConfigurationManager
.ConnectionStrings["ConnectionString"].ConnectionString;
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.
public static class Config
{
public static string ConnectionString
{
get
{
return WebConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString;
}
}
}
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.