I started to use the code to Add Settings to my WPF App on runtime. We have the following Class to add/read Custom Settings:
using System;
using System.Configuration;
namespace my.Classes
{
class AppSettingHandler
{
public static void ReadAllSettings()
{
try
{
var appSettings = ConfigurationManager.AppSettings;
if (appSettings.Count == 0)
{
Console.WriteLine("AppSettings is empty.");
}
else
{
foreach (var key in appSettings.AllKeys)
{
Console.WriteLine("Key: {0} Value: {1}", key, appSettings[key]);
}
}
}
catch (ConfigurationErrorsException)
{
Console.WriteLine("Error reading app settings");
}
}
public static void ReadSetting(string key)
{
try
{
var appSettings = ConfigurationManager.AppSettings;
string result = appSettings[key] ?? "Not Found";
Console.WriteLine(result);
}
catch (ConfigurationErrorsException)
{
Console.WriteLine("Error reading app settings");
}
}
public static void AddUpdateAppSettings(string key, string value)
{
try
{
var configFile = ConfigurationManager.OpenExeConfiguration(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");
}
}
}
}
And I like to add a new setting with name and value to my App.config with the following:
AppSettingHandler.AddUpdateAppSettings("MyCustom_Setting_" + item.DomaineName.ToString(), "Domaine: " + item.DomaineName);
I get no error and the data but my App isnt writing into the App.config. Did I miss something like to reload the Config?
Thank y