Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to read connection string setting from web.config
here is my sample code
C#
string connect= ConfigurationSettings.AppSettings["myconnection"];
    SqlConnection sqlConn = new SqlConnection(connect);
    sqlConn.Open();
    SqlCommand cmd = sqlConn.CreateCommand();


HTML
<appsettings>
       <connectionstrings>
    <add name="myconnection" connectionstring="server=SERVER1\\MSSQLSERVER2008;database=DataConverter;uid=sa;password=sa;" />
    </connectionstrings>
  </appsettings>


but it not working am using .net2.o and sqlserver2008
am unable to read connection string with the above syntax,am getting a Null string
Posted
Updated 4-Nov-11 4:10am
v4
Comments
Prerak Patel 4-Nov-11 8:11am    
Show part of your config file.

For 3.5
C#
//to read
ConnectionStringSettings connection = ConfigurationManager.ConnectionStrings["MyConnectionString"]
string connectionString = connection.ConnectionString


XML
<configuration>
<connectionStrings>
<add connectionString="" providerName="" name="MyConnectionString"/>
</connectionStrings>
</configuration>


For 2.0

XML
<appSettings>
<add key="myConnectionString" value=";" />
</appSettings>


C#
//to read
string connStr = ConfigurationSettings.AppSettings("myConnectionString");
 
Share this answer
 
v2
Or change your config as
XML
<appsettings>
      <add key="myconnection" value="server=SERVER1\\MSSQLSERVER2008;database=DataConverter;uid=sa;password=sa;"/>
</appsettings>


Ref: http://odetocode.com/code/345.aspx[^]
 
Share this answer
 
put your connection string in web.config
HTML
<appSettings>
<add key="myConnectionString" value="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</appSettings>


and retrive in code.
string connStr = ConfigurationSettings.AppSettings("myConnectionString");
 
Share this answer
 
Comments
pradeep manne 4-Nov-11 9:09am    
Hi am not getting the value of web config into the string connStr
XML
<AppSettings in web.config>
    <add key="FileUploadFolder" value="App_Uploaded_Files" />
    <add key="AppKey" value="Value in AppSetting key"/>
  </appSettings>


code behind
string folder_from_config = ConfigurationManager.AppSettings["FileUploadFolder"].ToString();
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900