@Kapanther , Welcome to Microsoft Q&A, based on my test, I reproduced your problem.
I recommend that you use the following code to change your app.config value.
private void btntest_Click(object sender, RoutedEventArgs e)
{
AddUpdateAppSettings("DatabaseName", "connstr");
AddUpdateAppSettings("DatabaseUsername", "testuser");
AddUpdateAppSettings("DatabasePassword", "password");
}
public void AddUpdateAppSettings(string key, string value)
{
try
{
System.Configuration.ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = AppDomain.CurrentDomain.BaseDirectory + "..\\..\\App.config";
Configuration configFile = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
var settings = configFile.AppSettings.Settings;
if (settings[key] == null)
{
settings.Add(key, value);
}
else
{
settings[key].Value = value;
}
configFile.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
}
catch (ConfigurationErrorsException)
{
Console.WriteLine("Error writing app settings");
}
}
Result:
Best Regards,
Jack
If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.