问题描述
我正在使用.NET Framework 4.6.1开发C#WPF MVVM应用程序,并且在App.config中有一个自定义部分:
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>
我想修改 PrinterSpeed
和 CameraSpeed
从我的应用中。我试过了这段代码:
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");
}
}
但这不起作用,因为我不是修改 AppSettings
部分。
But it doesn't work because I'm not modifying AppSettings
section.
如何修改这些值?
推荐答案
System.Configuration.NameValueSectionHandler
很难使用。您可以使用 System.Configuration.AppSettingsSection
替换它,而无需进行其他操作:
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");
}
}
这篇关于修改自定义app.config配置节并保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!