Reputation: 1233
I'm trying to programmatically add and save a key to my App.config file. My code is below, I've seen tons of different examples like this, and mine is not working. I'm trying to add a brand new key, not modify an existing. This is a console application, and I did make sure to add a Reference to System.configuration.
Program.cs
using System;
using System.Linq;
using System.Text;
using System.Configuration;
namespace AddValuesToConfig
{
class Program
{
static void Main(string[] args)
{
System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings.Add("key1", "value");
// Save the changes in App.config file.
config.Save(ConfigurationSaveMode.Modified);
}
}
}
App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
</appSettings>
</configuration>
Upvotes: 2
Views: 8041
Reputation: 15372
This worked for me:
ConfigurationManager.AppSettings.Set(item.Key, item.Value);
Upvotes: 0
Reputation: 289
for write:
public static bool SetAppSettings<TType>(string key, TType value)
{
try
{
if (string.IsNullOrEmpty(key))
return false;
Configuration appConfig = ConfigurationManager.OpenExeConfiguration(GetCurrentApplicationPath());
AppSettingsSection appSettings = (AppSettingsSection)appConfig.GetSection("appSettings");
if (appSettings.Settings[key] == null)
appSettings.Settings.Add(key, value.ToString());
else
appSettings.Settings[key].Value = value.ToString();
appConfig.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
return true;
}
catch
{
return false;
}
}
for read:
public static TType GetAppSettings<TType>(string key, TType defaultValue = default(TType))
{
try
{
if (string.IsNullOrEmpty(key))
return defaultValue;
AppSettingsReader appSettings = new AppSettingsReader();
return (TType)appSettings.GetValue(key, typeof(TType));
}
catch
{
return defaultValue;
}
}
Upvotes: 1
Reputation: 101583
Most likely you run this code under debugger in Visual Studio. Thing is when you do this, Visual Studio really runs not YourApp.exe, but YourApp.vshost.exe file. That means you are adding your key to YourApp.vshost.exe.config file instead of YourApp.exe.config. Try run without debugger, it should work then.
EDIT to answer comment below. Topic starter claims that VS does not write even to .vshost.exe.config when debugging, and I thought that is true. However little investigation shows that it DOES write to .vshost.config.exe file, BUT when you stop debugging, it will overwrite contents of your .vshost.exe.config with your .exe.config. So after your debugging session ends, you might think it did not write anything at all. However, if you put breakpoint right after config.Save() statement and open .vshost.exe.config file - you will see changes there.
Upvotes: 2