I am developing win forms and i have App config file .How can I write to connection strings section of app config file? My current App.Config file is
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="MyDbConnection" connectionString="" providerName="System.Data.OleDb" />
</connectionStrings>
</configuration>
and my C# code to change the Connection String is
var Config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connectionStringsSection = (ConnectionStringsSection)Config.GetSection("connectionStrings");
ConfigurationManager.ConnectionStrings["MyDbConnection"].ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FilePath + "";
Config.Save();
ConfigurationManager.RefreshSection("connectionStrings");
however Exception is generated at 3rd Line it is
configuration error exception this configuration is read only
The code to change connection strings is called from an external class.I dont know where should i place the code to override IsReadonly() method . Also app config does not have code behind file.
App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="MyDBConnectionString" providerName="System.Data.SqlClient"
connectionString="Data Source=localhost;Initial Catalog=MySQLServerDB; Integrated Security=true" />
</connectionStrings>
</configuration>
When you save your connection string in App.config file you can use System.Configuration.ConfigurationManager class to read this connection string in code.
ConnectionStringSettings conSettings = ConfigurationManager.ConnectionStrings["MyDBConnectionString"];
ConnectionStringsSettings class provides properties to read connection string settings in your program as follows:
string name = conSettings.Name;
string providerName = conSettings.ProviderName;
string connectionString = conSettings.ConnectionString;
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