gpt4 book ai didi

c# - 修改自定义 app.config 配置部分并保存

转载 作者:太空狗 更新时间:2023-10-30 01:31:35 25 4
gpt4 key购买 nike

我正在使用 .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>

我想从我的应用中修改 PrinterSpeedCameraSpeed。我试过这段代码:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com