I'm creating an application on .net framework 4.5
whenever i want to load the app config values (appSettings section) and write the changes, i don't see my changes if i refresh the section. What i am doing wrong? and how can i solve it?
code
private void LoadConfig()
{
NameValueCollection appSettings = ConfigurationManager.AppSettings;
for (int i = 0; i < appSettings.Count; i++)
{
switch (appSettings.GetKey(i))
{
case "initialCatalog":
txtInitialCatalog.Text = appSettings.GetValues(i)[0];
break;
case "dataSource":
txtDatasource.Text = appSettings.GetValues(i)[0];
break;
case "userName":
txtUsername.Text = appSettings.GetValues(i)[0];
break;
case "password":
txtPassword.Text = appSettings.GetValues(i)[0];
break;
case "portalUrl":
txtUrl.Text = appSettings.GetValues(i)[0];
break;
}
}
}
private void SaveConfig()
{
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
KeyValueConfigurationCollection appSettings = config.AppSettings.Settings;
appSettings["initialCatalog"].Value = txtInitialCatalog.Text;
appSettings["dataSource"].Value = txtDatasource.Text;
appSettings["userName"].Value = txtUsername.Text;
appSettings["password"].Value = txtPassword.Text;
appSettings["portalUrl"].Value = txtUrl.Text;
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
}
App.config file
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<appSettings>
<add key="initialCatalog" value="a" />
<add key="dataSource" value="b" />
<add key="password" value="c" />
<add key="userName" value="d" />
<add key="portalUrl" value="e" />
<add key="poolingTime" value="60000" />
<add key="ClientSettingsProvider.ServiceUri" value="" />
</appSettings>
i call ReadConfig() when the forms is Activated and save the data when a button is pressed (Ok or Apply) i close the application i rerun it but no changes are made to the app.config file
any ideas???
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.
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