Alex Rivera | Logout

.net 3.5: To read connectionstring from app.config?

Asked 2009-12-02T07:53:57.800
10

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> 
Edit
Report

1 Answer

4

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();
        }
answered 2009-12-02T07:59:20.630

Your Answer