Reputation: 3974
I am trying to programmatically update the connections string in my App.config file.
I can read the value perfectly but I cannot seem to update the value for some reason.
My App.config look like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<connectionStrings>
<add name="TPAPI.Properties.Settings.TruePotentialConnectionString"
connectionString="Data Source=(local);Initial Catalog=TruePotential;User ID=sa;Password=password"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
I can read it with this:
txtConnectionString.Text = System.Configuration.ConfigurationManager.ConnectionStrings["TPAPI.Properties.Settings.TruePotentialConnectionString"].ConnectionString;
BUT when I try and write a new value nothing happens.
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings["TPAPI.Properties.Settings.TruePotentialConnectionString"].ConnectionString = txtConnectionString.Text;
config.Save(ConfigurationSaveMode.Modified, true);
ConfigurationManager.RefreshSection("connectionStrings");
Can anyone see what I am doing wrong please?
Upvotes: 0
Views: 3559
Reputation: 956
I'm not sure if this is the same problem as u have but if u want u can read this for a moment, It's not my own answer.
Credits:
https://stackoverflow.com/a/13133034/3239917
I think what is happening is that you are testing in Visual Studio, it copys the App.Config to your Debug/Release directory and renames it YourApplication.vshost.exe.config which gets reset each time you start your application. Try running the executable outside of Visual Studio which will use the YourApplication.exe.config file and see if that works for you. Your Code is working for me and retaining your changes on application restart if I run it outside of Visual Studio.
Upvotes: 3