2011-09-04 61 views
1

我試過我第一次在app.settings中使用自定義配置。當我嘗試調用配置時,出現「無法識別的配置節服務器」。我究竟做錯了什麼?app.settings自定義配置問題

<?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"> 
     <sectionGroup name="servers" type="System.Configuration.NameValueSectionHandler"></sectionGroup> 
     <sectionGroup name="services" type="System.Configuration.NameValueSectionHandler"></sectionGroup> 
     <!--<section name="servers.myServers" type="System.Configuration.NameValueFileSectionHandler" />--> 
     <!--<section name="services.myServices" type="System.Configuration.NameValueFileSectionHandler" />--> 
     <section name="ServiceMonitor.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" /> 
    </sectionGroup> 
    </configSections> 

    <servers> 
    <myServers> 
     <add key="server1" value="myserverhost"/> 
    </myServers> 
    </servers> 

    <services> 
    <myServices> 
     <add key="service1" value="spooler"/> 
     <add key="service2" value="Apple Mobile Device"/> 
    </myServices> 
    </services> 

    <userSettings> 
    <ServiceMonitor.Properties.Settings> 
     <setting name="service1" serializeAs="String"> 
     <value>spooler</value> 
     </setting> 
     <setting name="service2" serializeAs="String"> 
     <value>Apple Mobile Device</value> 
     </setting> 
    </ServiceMonitor.Properties.Settings> 
    </userSettings> 
    <appSettings> 
    <add key="service1" value="spooler"/> 
    <add key="service2" value="Apple Mobile Device"/> 
    </appSettings> 

</configuration> 

這裏是我用來調用配置的C#代碼。

NameValueCollection settings = ConfigurationManager.GetSection("servers/myServers") as NameValueCollection; 
if (settings != null) 
{ 
    foreach (string key in settings) 
    { 
     Console.WriteLine("{0} : {1}", key, settings[key]); 
    } 
} 
+4

如果您的文件被命名爲「app.settings」,那麼這就解釋了爲什麼它不起作用。你希望它被命名爲「app.config」。 –

+0

我注意到你沒有完全合格的班級名稱;這可能是問題(雖然不確定,但我會把它放進去)。 –

回答

1

我認爲你需要添加的部分元素(這是在你的例子註釋掉):

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
    <configSections> 
    <sectionGroup name="services"> 
     <section name="myServices" 
     type="System.Configuration.NameValueSectionHandler" />    
    </sectionGroup> 
    </configSections> 
</configuration> 

爲例見sectionGroup Element for configSections

+0

它已經掛在我的usersettings部分。無論如何,我不需要它,所以我將它剝離出來,現在它正在工作。 – Dovey

+0

@Dovey,你應該用解決方案回答你的問題並接受答案。 –