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");
How to change values in config file dynamically in react?
You can accomplish it by using the state hook. Here's an example (You can see my code in action here: https://codesandbox.io/s/thirsty-keller-cjqb8):
// put this in config.js
const initialConfig = {
darkMode: true
};
const App = () => {
// dark mode is initally true, because we used the config value as inital value for darkMode
const [darkMode, setDarkMode] = useState(initialConfig.darkMode);
// change handler that is invoked when we change the value of the checkbox
const changeMode = ({ currentTarget: { checked } }) => setDarkMode(checked);
return (
// use className based on the value of darkMode
<div className={darkMode ? "darkMode" : ""}>
<label>
<input checked={darkMode} type="checkbox" onChange={changeMode} />
use dark mode
</label>
</div>
);
};
I used the config as an inital value. However, you need a state that stores the information which mode is currently active.
How to dynamically apply changes to app.config on program start?
You're not using the Config file appropriately. Try this:
<configuration>
...
<appSettings>
<add key="EnvUnderTest" value="settings_a.xml" />
</appSettings>
...
</configuration>
This should work with the code you've provided. Obviously, any other key you wish to add should also be under <appSettings>
.
Change default app.config at runtime
The hack in the linked question works if it is used before the configuration system is used the first time. After that, it doesn't work any more.
The reason:
There exists a class ClientConfigPaths
that caches the paths. So, even after changing the path with SetData
, it is not re-read, because there already exist cached values. The solution is to remove these, too:
using System;
using System.Configuration;
using System.Linq;
using System.Reflection;
public abstract class AppConfig : IDisposable
{
public static AppConfig Change(string path)
{
return new ChangeAppConfig(path);
}
public abstract void Dispose();
private class ChangeAppConfig : AppConfig
{
private readonly string oldConfig =
AppDomain.CurrentDomain.GetData("APP_CONFIG_FILE").ToString();
private bool disposedValue;
public ChangeAppConfig(string path)
{
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", path);
ResetConfigMechanism();
}
public override void Dispose()
{
if (!disposedValue)
{
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", oldConfig);
ResetConfigMechanism();
disposedValue = true;
}
GC.SuppressFinalize(this);
}
private static void ResetConfigMechanism()
{
typeof(ConfigurationManager)
.GetField("s_initState", BindingFlags.NonPublic |
BindingFlags.Static)
.SetValue(null, 0);
typeof(ConfigurationManager)
.GetField("s_configSystem", BindingFlags.NonPublic |
BindingFlags.Static)
.SetValue(null, null);
typeof(ConfigurationManager)
.Assembly.GetTypes()
.Where(x => x.FullName ==
"System.Configuration.ClientConfigPaths")
.First()
.GetField("s_current", BindingFlags.NonPublic |
BindingFlags.Static)
.SetValue(null, null);
}
}
}
Usage is like this:
// the default app.config is used.
using(AppConfig.Change(tempFileName))
{
// the app.config in tempFileName is used
}
// the default app.config is used.
If you want to change the used app.config for the whole runtime of your application, simply put AppConfig.Change(tempFileName)
without the using somewhere at the start of your application.
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();
Related Topics
Differencebetween Casting and Coercing
How to Import from Excel to a Dataset Using Microsoft.Office.Interop.Excel
Why Are Some Members Missing When Trying to Print an Object by Serializing to JSON
How to Get a Count of the Total Number of Digits in a Number
Converting String to Float in C#
C# Pass Lambda Expression as Method Parameter
Show Controls Added Programmatically in Winforms App in Design View
Practical Usage of Virtual Functions in C#
Deserializing Heterogenous JSON Array into Covariant List<> Using JSON.Net
Resharper Conventions for Names of Event Handlers
How to Make a Wizard with ASP.NET MVC
Static Property Using Inotifypropertychanged. C#
Learning Single Responsibility Principle with C#
How to Create a C# App That Decides Itself Whether to Show as a Console or Windowed App
Sqlite Keeps the Database Locked Even After the Connection Is Closed