views:

2582

answers:

3

How to read connection string info from app.config file using .net api?

Platform is .net 3.5

     <?xml version="1.0" encoding="utf-8" ?>
        <configuration>
            <connectionStrings>
                 <add connectionString="" providerName="" name=""/>
            </connectionStrings>
        </configuration>
+1  A: 

If name is a string value that represents the name of the connection string:

var connectionString = 
    ConfigurationManager.ConnectionStrings[name].ConnectionString;

In your example you didn't provide a value for name, so you'll have to do that before it'll work.

Mark Seemann
+1  A: 

In the config:

<add name="ConnectionName" connectionString="Data Source=xxxx\yyyy;Initial Catalog=MyDB;User ID=userName;Password=pwd" />

In C# code:

    using System.Configuration;

...

    string connectionString = ConfigurationManager.ConnectionStrings["ConnectionName"].ToString();

Better still would be to define a function and use it in the code everywhere:

public string getConnectionStringMyDB()
        {
            return ConfigurationManager.ConnectionStrings["ConnectionName"].ToString();
        }
Rashmi Pandit
+1  A: 

Please see http://www.davidhayden.com/blog/dave/archive/2007/02/22/ReadConnectionStringsWebConfigAppConfig.aspx:

ConnectionStringSettings connection = ConfigurationManager.ConnectionStrings["MyConnectionString"]
string connectionString = connection.ConnectionString

You may need to add an assembly reference to System.Configuration

Kragen