Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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> 
like image 825
Maddy.Shik Avatar asked Dec 02 '09 07:12

Maddy.Shik


2 Answers

Please see Reading Connection Strings in Web.Config and App.Config and Enterprise Library DAAB Settings (on the Wayback Machine as the original got deleted)

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

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

like image 171
Justin Avatar answered Nov 01 '22 00:11

Justin


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();
        }
like image 21
SO User Avatar answered Nov 01 '22 01:11

SO User