【发布时间】:2014-03-26 08:05:33
【问题描述】:
我在从应用配置中读取自定义部分时遇到问题。 我有
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>
文件夹配置.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。我无法理解我做错了什么。请帮忙
【问题讨论】:
标签: .net app-config