ConfigurationManager - 如何从.exe.config读取值

时间:2016-10-13 04:41:49

标签: c# .net c#-4.0 visual-studio-2015

我正在开发一款允许用户管理Windows程序的应用。

所以我有一个.exe.config文件并包含这个:

<?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>

我想阅读并更改valeus,但是,没有成功,没有保存更改,我无法读取任何值,当我尝试时,程序抛出一个System.NullReferenceException,这是我的代码:

        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);
            }

所以,在第二行,我得到了例外,没有任何作用,任何帮助?

提前致谢!

1 个答案:

答案 0 :(得分:1)

第二行的

config.AppSettings从配置文件中的<appSettings>节点读取。并且配置文件中没有<appSettings>节点。

检查this link以解决您的问题。