ConfigurationManager.AppSettings - How to modify and save?
Perhaps you should look at adding a Settings File. (e.g. App.Settings)
Creating this file will allow you to do the following:
string mysetting = App.Default.MySetting;
App.Default.MySetting = "my new setting";
This means you can edit and then change items, where the items are strongly typed, and best of all... you don't have to touch any xml before you deploy!
The result is a Application or User contextual setting.
Have a look in the "add new item" menu for the setting file.
ConfigurationManager doesn't save settings
I think you should call the Save method
ConfigurationManager.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
EDIT
To be able to save you have to use a configuration object returned by the OpenExeConfiguration Method
//Create the object
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
//make changes
config.AppSettings.Settings["Username"].Value = txtUsername.Text;
config.AppSettings.Settings["Password"].Value = txtPassword.Text;
//save to apply changes
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
More references here ConfigurationManager Class
ConfigurationManager not saving value in app.config
That will not update it, you have save the changes back to config file following way:
Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
configuration.AppSettings.Settings["Volume"].Value = volumeNumSlider.Value.ToString();
configuration.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
C# ConfigurationManager does not save changes
your code looks correct - but make sure you are looking at the right file. Inspect config.FilePath
in debugger to see what file you are changing.
most likely you run your app from VS - and expect it to update your project root\app.config
file - but the file you are updating is project root\bin\debug\app.config
How to Modify AppSettings key value at run time?
App.Config
file value will revert back each time you rebuild the solution. This will only work as desired when you deploy your application.
Or You can
Add key to Settings.settings
like below.
Write to it like this;
ModelCodeGenerator.Properties.Settings.Default.DefaultTargetPath = txtFolder.Text;
ModelCodeGenerator.Properties.Settings.Default.Save();
ModelCodeGenerator
is my solution name.
How to save changes in App.config?
For Winforms projects, when you compile your project the app.config
file is copied to the output directory as <appname>.exe.config
. Any runtime changes made to the configuration are made to this file (and not the app.config
in your source code directory). This is the file that should be distributed with your application; if you're using ClickOnce this file will go with your application to become the config file used by the deployment.
Also worth noting for debugging purposes (which is really your use case here for the moment), as long as you're running inside Visual Studio, the actual file modified will be <appname>.vshost.exe.config
. You can verify this by running inside VS and checking the .vshost.exe.config file, and then running the .exe from the directory directly and monitoring the .exe.config file.
As for the InvalidOperationException
, there is a known problem with trying to access the app.config file in a VirtualBox shared folder, although the only solution seems to be to use a local directory.
App.Config change value
You cannot use AppSettings static object for this. Try this
string appPath = System.IO.Path.GetDirectoryName(Reflection.Assembly.GetExecutingAssembly().Location);
string configFile = System.IO.Path.Combine(appPath, "App.config");
ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
configFileMap.ExeConfigFilename = configFile;
System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
config.AppSettings.Settings["YourThing"].Value = "New Value";
config.Save();
How to Update (Add/Modify/Delete) keys in AppSettings section of web.config at runtime
Thanks to nkvu which directed me to a his first link which in turn sent me to Williarob's post "Override Configuration Manager" I managed to find a solution to my question.
The mentioned blog post covers how to read settings from another XML file and it works with both windowed applications and web applications (with a little modification in config file name and path). Although this blog written on 2010 it is still working fine with .NET4 without problem.
However as I was going to read my configuration from a secure device, I simplified the class and here is how to use the classes provided by Williarob
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Configuration.Internal;
using System.Linq;
using System.Reflection;
namespace Williablog.Core.Configuration {
public sealed class ConfigSystem: IInternalConfigSystem {
private static IInternalConfigSystem clientConfigSystem;
private object appsettings;
private object connectionStrings;
/// <summary>
/// Re-initializes the ConfigurationManager, allowing us to merge in the settings from Core.Config
/// </summary>
public static void Install() {
FieldInfo[] fiStateValues = null;
Type tInitState = typeof(System.Configuration.ConfigurationManager).GetNestedType("InitState", BindingFlags.NonPublic);
if (null != tInitState) {
fiStateValues = tInitState.GetFields();
}
FieldInfo fiInit = typeof(System.Configuration.ConfigurationManager).GetField("s_initState", BindingFlags.NonPublic | BindingFlags.Static);
FieldInfo fiSystem = typeof(System.Configuration.ConfigurationManager).GetField("s_configSystem", BindingFlags.NonPublic | BindingFlags.Static);
if (fiInit != null && fiSystem != null && null != fiStateValues) {
fiInit.SetValue(null, fiStateValues[1].GetValue(null));
fiSystem.SetValue(null, null);
}
ConfigSystem confSys = new ConfigSystem();
Type configFactoryType = Type.GetType("System.Configuration.Internal.InternalConfigSettingsFactory, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", true);
IInternalConfigSettingsFactory configSettingsFactory = (IInternalConfigSettingsFactory) Activator.CreateInstance(configFactoryType, true);
configSettingsFactory.SetConfigurationSystem(confSys, false);
Type clientConfigSystemType = Type.GetType("System.Configuration.ClientConfigurationSystem, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", true);
clientConfigSystem = (IInternalConfigSystem) Activator.CreateInstance(clientConfigSystemType, true);
}
#region IInternalConfigSystem Members
public object GetSection(string configKey) {
// get the section from the default location (web.config or app.config)
object section = clientConfigSystem.GetSection(configKey);
switch (configKey) {
case "appSettings":
// Return cached version if exists
if (this.appsettings != null) {
return this.appsettings;
}
// create a new collection because the underlying collection is read-only
var cfg = new NameValueCollection();
// If an AppSettings section exists in Web.config, read and add values from it
if (section is NameValueCollection) {
NameValueCollection localSettings = (NameValueCollection) section;
foreach (string key in localSettings) {
cfg.Add(key, localSettings[key]);
}
}
// --------------------------------------------------------------------
// Here I read and decrypt keys and add them to secureConfig dictionary
// To test assume the following line is a key stored in secure sotrage.
//secureConfig = SecureConfig.LoadConfig();
secureConfig.Add("ACriticalKey", "VeryCriticalValue");
// --------------------------------------------------------------------
foreach (KeyValuePair<string, string> item in secureConfig) {
if (cfg.AllKeys.Contains(item.Key)) {
cfg[item.Key] = item.Value;
} else {
cfg.Add(item.Key, item.Value);
}
}
// --------------------------------------------------------------------
// Cach the settings for future use
this.appsettings = cfg;
// return the merged version of the items from secure storage and appsettings
section = this.appsettings;
break;
case "connectionStrings":
// Return cached version if exists
if (this.connectionStrings != null) {
return this.connectionStrings;
}
// create a new collection because the underlying collection is read-only
ConnectionStringsSection connectionStringsSection = new ConnectionStringsSection();
// copy the existing connection strings into the new collection
foreach (ConnectionStringSettings connectionStringSetting in ((ConnectionStringsSection) section).ConnectionStrings) {
connectionStringsSection.ConnectionStrings.Add(connectionStringSetting);
}
// --------------------------------------------------------------------
// Again Load connection strings from secure storage and merge like below
// connectionStringsSection.ConnectionStrings.Add(connectionStringSetting);
// --------------------------------------------------------------------
// Cach the settings for future use
this.connectionStrings = connectionStringsSection;
// return the merged version of the items from secure storage and appsettings
section = this.connectionStrings;
break;
}
return section;
}
public void RefreshConfig(string sectionName) {
if (sectionName == "appSettings") {
this.appsettings = null;
}
if (sectionName == "connectionStrings") {
this.connectionStrings = null;
}
clientConfigSystem.RefreshConfig(sectionName);
}
public bool SupportsUserConfig { get { return clientConfigSystem.SupportsUserConfig; } }
#endregion
}
}
To install this (or original version of configuration override) add following line to
your Global. class (Global.asax.cs) in Application_Start
Williablog.Core.Configuration.ConfigSystem .Install();
like below:
public class Global: System.Web.HttpApplication {
//...
#region protected void Application_Start(...)
protected void Application_Start(object sender, EventArgs e) {
Williablog.Core.Configuration.ConfigSystem .Install();
//...
}
#endregion
//...
}
How to update app settings key value pair dynamically on app.config file in c# winforms
Configuration configuration = ConfigurationManager.
OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
configuration.AppSettings.Settings["logPath"].Value = DateTime.Now.ToString("yyyy-MM-dd");
configuration.Save();
ConfigurationManager.RefreshSection("appSettings");
Related Topics
Preprocessor Directive in C# for Importing Based on Platform
How to Take the Cartesian Join of Two Lists in C#
Convert Am/Pm Time to 24 Hours Format
Newtonsoft JSON.Net Serialize Jobject Doesn't Ignore Nulls, Even with the Right Settings
C# Object Initialization of Read Only Collection Properties
Group by Variable Integer Range Using Linq
PDF Compression with Itextsharp
Overloaded Method-Group Argument Confuses Overload Resolution
How Does One Extract Each Folder Name from a Path
Using Statement with Generics: Using Iset<> = System.Collections.Generic.Iset<>
Reading from a Text File in C#
Enumerating Through an Object's Properties (String) in C#
How to Create Custom Propertygrid Editor Item Which Opens a Form
How to Use More Than One Processor Group for My Threads in a C# App
@(At) Sign in File Path/String
When to Use Enums, and When to Replace Them with a Class with Static Members