ConfigurationManager -如何从.exe.config中读取值
本文关键字:config 读取 exe ConfigurationManager | 更新日期: 2023-09-27 18:12:47
我正在开发一个允许用户管理Windows程序的应用程序。
所以我有一个。exe。配置文件并包含以下内容:
<?xml version="1.0" encoding="utf-8" ?><configuration>
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="Control_Desk.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<userSettings>
<Control_Desk.Properties.Settings>
<setting name="enabletw" serializeAs="String">
<value>True</value>
</setting>
<setting name="enablelivemail" serializeAs="String">
<value>True</value>
</setting>
<setting name="enabledesktop" serializeAs="String">
<value>True</value>
</setting>
<setting name="enablelogmein" serializeAs="String">
<value>True</value>
</setting>
<setting name="enableps" serializeAs="String">
<value>False</value>
</setting>
<setting name="enablecorel" serializeAs="String">
<value>False</value>
</setting>
<setting name="enablescanner" serializeAs="String">
<value>False</value>
</setting>
</Control_Desk.Properties.Settings>
</userSettings>
我想读取和更改值,但是,没有成功,没有更改保存,我不能读取任何值,当我尝试时,程序抛出系统。下面是我的代码:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (config.AppSettings.Settings["enablelivemail"].Value == "True")
{
config.AppSettings.Settings["enablelivemail"].Value = "False";
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name);
//ConfigurationManager.RefreshSection("appSettings");
}
else
{
config.AppSettings.Settings["enablelivemail"].Value = "True";
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name);
}
所以,在第二行我得到了异常,没有任何工作,有帮助吗?
提前感谢!
第二行config.AppSettings
从配置文件中的<appSettings>
节点读取。在你的配置文件中没有<appSettings>
节点。
点击此链接解决您的问题