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>
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
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With