2016-10-13 100 views
0

我正在開發一個允許用戶管理Windows程序的應用程序。ConfigurationManager - 如何從.exe.config中讀取值

所以我有一個.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,但是,沒有sucess,不改變被保存,我不能讀取任何值,當我嘗試,程序拋出一個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); 
      } 

因此,在第二行我得到了異常,並沒有什麼作品,任何幫助嗎?

在此先感謝!

+0

http://stackoverflow.com/a/11149569/3583859請參閱本文,將有助於 –

+0

@VijayKumbhoje,您是否嘗試過OP的使用案例解決方案 –

回答

1

config.AppSettings在第二行讀取配置文件中的<appSettings>節點。在配置文件中沒有<appSettings>節點。

檢查this link解決您的問題。

+0

您需要開始解釋解決方案,其中單獨的Section Group和部分創建,因爲'userSettings'不是一個標準組和'Control_Desk.Properties.Settings',而不是標準部分 –