I'm developing a C# WPF MVVM application with .NET Framework 4.6.1 and I have a custom section in App.config:
<configuration>
<configSections>
<section name="SpeedSection" type="System.Configuration.NameValueSectionHandler" />
</configSections>
<SpeedSection>
<add key="PrinterSpeed" value="150" />
<add key="CameraSpeed" value="150" />
</SpeedSection>
</configuration>
I want to modify PrinterSpeed
and CameraSpeed
from my app. I have tried this code:
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");
}
}
But it doesn't work because I'm not modifying AppSettings
section.
How can I modify those values?
Save(ConfigurationSaveMode, Boolean) Writes the configuration settings contained within this Configuration object to the current XML configuration file.
Open the App. config file and add the configSections, sectionGroup and section to it. We need to specify the name and fully qualified type of all the section and section group.
The file is stored inside this path "bin/debug/app. config", if you make changes while debugging, those changes should appear there. Just remember that this file is overwritten with the "app. config" from the project root each time you run the application on Visual Studio IDE.
System.Configuration.NameValueSectionHandler
is hard to work with. You can replace it with System.Configuration.AppSettingsSection
without touching anything else:
<configuration>
<configSections>
<section name="SpeedSection" type="System.Configuration.AppSettingsSection" />
</configSections>
<SpeedSection>
<add key="PrinterSpeed" value="150" />
<add key="CameraSpeed" value="150" />
</SpeedSection>
</configuration>
And then change your method as follows:
static void AddUpdateAppSettings(string key, string value)
{
try
{
var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var settings = ((AppSettingsSection) configFile.GetSection("SpeedSection")).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");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With