我正在使用 .NET Framework 4.6.1 开发 C# WPF MVVM 应用程序,我在 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
。我试过这段代码:
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
部分。
如何修改这些值?
最佳答案
System.Configuration.NameValueSectionHandler
很难使用。您可以将其替换为 System.Configuration.AppSettingsSection
而无需触及任何其他内容:
<configuration>
<configSections>
<section name="SpeedSection" type="System.Configuration.AppSettingsSection" />
</configSections>
<SpeedSection>
<add key="PrinterSpeed" value="150" />
<add key="CameraSpeed" value="150" />
</SpeedSection>
</configuration>
然后改变你的方法如下:
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");
}
}
关于c# - 修改自定义 app.config 配置部分并保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40737395/