从app config读取自定义部分时遇到问题。 我有
的app.config:
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="StartupFolders" type="Test.FolderConfiguration, Test"/>
</sectionGroup>
</configSections>
<applicationSettings>
<StartupFolders>
<Folders>
<Folder folderType="A" path="c:\foo" />
<Folder folderType="B" path="C:\foo1" />
</Folders>
</StartupFolders>
</applicationSettings>
</configuration>
FolderConfiguration.cs:
namespace Test
{
public class FolderElement : ConfigurationElement
{
[ConfigurationProperty("folderType", DefaultValue = "", IsKey = true, IsRequired = true)]
public string FolderType
{
get { return ((string)(base["folderType"])); }
set { base["folderType"] = value; }
}
[ConfigurationProperty("path", DefaultValue = "", IsKey = false, IsRequired = false)]
public string Path
{
get { return ((string)(base["path"])); }
set { base["path"] = value; }
}
}
[ConfigurationCollection(typeof(FolderElement))]
public class FoldersCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new FolderElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((FolderElement)(element)).FolderType;
}
public FolderElement this[int idx]
{
get { return (FolderElement)BaseGet(idx); }
}
}
class FolderConfiguration : ConfigurationSection
{
[ConfigurationProperty("Folders")]
public FoldersCollection FolderItems
{
get { return ((FoldersCollection)(base["Folders"])); }
}
}
}
最后在MainWindow.cs中我使用它像:
Configuration cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
FolderConfiguration section = (FolderConfiguration)cfg.Sections["StartupFolders"];
它返回 section == null 。我无法理解我做错了什么。请帮忙
答案 0 :(得分:0)
class FolderConfiguration : ConfigurationSection
{
[ConfigurationProperty("Folders")]
[ConfigurationCollection(typeof(FoldersCollection), AddItemName = "Folder"]
public FoldersCollection Folders
{
get { return ((FoldersCollection)(base["Folders"])); }
}
}
另外,在您的FolderElements属性中,您有:
get { return ((string)(base["folderType"])); }
set { base["folderType"] = value; }
应该是:
get { return ((string)(this["folderType"])); }
set { this["folderType"] = value; }
这对你有帮助吗?
修改强>
我的答案是this
这会返回什么吗? var folderConfig = ConfigurationManager.GetSection(“StartupFolders”)as FolderConfiguration; if(folderConfig!= null){//循环收集}
答案 1 :(得分:0)
请查看this question。它只有一个级别(在参考问题中它是用户)但我没有看到StartupFolders-&gt;文件夹 - &gt;文件夹的原因。那你就可以只有
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="Folders" type="ConsoleApplication1.FoldersConfigMapSection, ConsoleApplication1"/>
</configSections>
<Folders>
<Folder folderType="A" path="c:\foo" />
<Folder folderType="B" path="C:\foo1" />
</Folders>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>