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
When you save your connection string in App.config file you can use System.Configuration.ConfigurationManager class to read this connection string in code.
ConnectionStringsSettings class provides properties to read connection string settings in your program as follows: