This blog article shows you how to add value to App.config during runtime and get the value back. This works for sure for .NET Framework. I am still finding how to do this for .NET Core. In fact, I just got some disappointing fact that this might not happen and people ask you to go for json file. So again, you are Framework or you are core. Write once run everywhere is hard to happen. Nevertheless, let’s look at App.config that existed and good to use for many years.
I have partial App.config file like the one below.
<appSettings>
<add key=“1” value=“fpx“ />
<add key=“6” value=“creditcard/6“ />
</appSettings>
I have a GetAppSetting method to get the AppSettings value.
public static void GetAppSetting(string value)
{
string str = System.Configuration.ConfigurationManager.AppSettings[value];
Console.WriteLine(str);
}
I have a AddKey method to add the new value to App.config during run time. It is actually added to ConAppSetting.exe.Config in the bin folder. ConAppSetting. is my project name.
public static void AddKey()
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings.Add(“6”, “creditcard/6”);
config.Save(ConfigurationSaveMode.Modified,true);
ConfigurationManager.RefreshSection(“appSettings”);
}
To test the code, you can use the main function like the one below.
static void Main(string[] args)
{
GetAppSetting(“1”);
AddKey();
GetAppSetting(“6”);
Console.WriteLine(“Press any key to continue…”);
Console.ReadKey();
}
You will see new entry added to the file.
<appSettings>
<add key=“1” value=“fpx“ />
<add key=“6” value=“creditcard/6“ />
</appSettings>
Source code: https://github.com/chanmmn/AppConfig
Pingback: exePath must be specified when not running inside a stand alone exe | Chanmingman's Blog