在ConfigurationSection中自定义IEnumerable

时间:2013-02-07 08:56:26

标签: c# configuration app-config

我需要在其中创建一个带有IEnumerable的简单自定义ConfigurationSection。

我已经阅读了几篇文章和stackoverflow链接,以此为例: How to create custom config section in app.config?

所以,我在Console App中有这个配置文件部分:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="Disk"
             type="ConsoleApplication1_ConfigurationEnumerable.PathsConfigSection"/>
  </configSections>
  <Disk>
    <Paths>
      <Path name="one" permission="1" />
      <Path name="two" permission="2" />
      <Path name="three" permission="3" />
    </Paths>
  </Disk>
</configuration>

接下来我有整个结构来管理配置部分:     使用System.Configuration;

namespace ConsoleApplication1_ConfigurationEnumerable
{
    public class Path: ConfigurationElement
    {
        [ConfigurationProperty("name", IsRequired = true)]
        public string Name
        {
            get
            {
                return (string)this["name"];
            }
        }

        [ConfigurationProperty("permission", IsRequired=true)]
        public string Permission
        {
            get
            {
                return (string)this["permission"];
            }
        }
    }    

    public class Paths: ConfigurationElementCollection 
    {
        public Path this[int index] 
        {
            get
            {
                return base.BaseGet(index) as Path;
            }
            set 
            {
                if (base.BaseGet(index) != null) {
                    base.BaseRemoveAt(index);
                }
                this.BaseAdd(index, value);
            }
        }

        protected override ConfigurationElement CreateNewElement() 
        {
            return new Path();
        }
        protected override object  GetElementKey(ConfigurationElement element)
        {
            return ((Path)element).Name;
        }
    }

    public class PathsConfigSection : ConfigurationSection
    {
        public static PathsConfigSection GetConfig()
        {
            //return (PathsConfigSection)System.Configuration.ConfigurationManager.GetSection("Disk") ?? new PathsConfigSection();
            return (PathsConfigSection)System.Configuration.ConfigurationManager.GetSection("Paths") ?? new PathsConfigSection();
        }

        [ConfigurationProperty("Paths")]
        public Paths Paths
        {
            get 
            {
                object o = this["Paths"];
                return o as Paths;
            }
        }
    }
}

这里的program.cs使用了整个东西: 使用System;

namespace ConsoleApplication1_ConfigurationEnumerable
{
    class Program
    {
        static void Main(string[] args)
        {
            var config = PathsConfigSection.GetConfig();
            if (config == null || config.Paths.Count == 0)
            {
                Console.WriteLine("Is null or empty");
            }
            else
            {
                foreach (Path item in config.Paths)
                {
                    Console.WriteLine("Item {0} with valuer {1}", item.Name, item.Permission);
                }
            }
        }
    }
}

这里的问题在于这两行:

//return (PathsConfigSection)System.Configuration
//       .ConfigurationManager.GetSection("Disk") ?? new PathsConfigSection();
return (PathsConfigSection)System.Configuration
       .ConfigurationManager.GetSection("Paths") ?? new PathsConfigSection();

如果我使用第二个(上面未注释),则返回null。

如果我使用评论的那个,那么它会抛出这样的异常:

  

System.Configuration.ConfigurationErrorsException未处理
  HResult = -2146232062消息=创建时出错   磁盘的配置节处理程序:无法加载类型   &#39; ConsoleApplication1_ConfigurationEnumerable.PathsConfigSection&#39;从   assembly&#39; System.Configuration,Version = 4.0.0.0,Culture = neutral,   公钥= b03f5f7f11d50a3a&#39 ;.   (C:\用户\黑莓\桌面\ ConsoleApplication1_ConfigurationEnumerable \ ConsoleApplication1_ConfigurationEnumerable \ BIN \调试\ ConsoleApplication1_ConfigurationEnumerable.vshost.exe.config   第4行Source = System.Configuration BareMessage =发生错误   为磁盘创建配置节处理程序:无法加载   type&#39; ConsoleApplication1_ConfigurationEnumerable.PathsConfigSection&#39;   来自assembly&System; System.Configuration,Version = 4.0.0.0,Culture = neutral,   公钥= b03f5f7f11d50a3a&#39 ;.
  文件名= C:\用户\黑莓\桌面\ ConsoleApplication1_ConfigurationEnumerable \ ConsoleApplication1_ConfigurationEnumerable \ BIN \调试\ ConsoleApplication1_ConfigurationEnumerable.vshost.exe.config   Line = 4 StackTrace:          at System.Configuration.BaseConfigurationRecord.FindAndEnsureFactoryRecord(String   configKey,布尔&amp; isRootDeclaredHere)          在System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String   configKey,Boolean getLkg,Boolean checkPermission,Boolean   getRuntimeObject,Boolean requestIsHere,Object&amp;结果,对象&amp;   resultRuntimeObject)          在System.Configuration.BaseConfigurationRecord.GetSection(String   configKey)          at System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(String   sectionName)          在System.Configuration.ConfigurationManager.GetSection(String sectionName)          在ConsoleApplication1_ConfigurationEnumerable.PathsConfigSection.GetConfig()   在   C:\用户\黑莓\桌面\ ConsoleApplication1_ConfigurationEnumerable \ ConsoleApplication1_ConfigurationEnumerable \ Disk.cs:行   63          在ConsoleApplication1_ConfigurationEnumerable.Program.Main(String []   args)in   C:\用户\黑莓\桌面\ ConsoleApplication1_ConfigurationEnumerable \ ConsoleApplication1_ConfigurationEnumerable \的Program.cs:行   9          在System.AppDomain._nExecuteAssembly(RuntimeAssembly程序集,String [] args)          在System.AppDomain.ExecuteAssembly(String assemblyFile,Evidence assemblySecurity,String [] args)          在Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()          在System.Threading.ThreadHelper.ThreadStart_Context(对象状态)          在System.Threading.ExecutionContext.RunInternal(ExecutionContext   executionContext,ContextCallback回调,对象状态,布尔值   preserveSyncCtx)          at System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback callback,Object state,Boolean   preserveSyncCtx)          在System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback回调,对象状态)          at System.Threading.ThreadHelper.ThreadStart()InnerException:System.TypeLoadException          的HResult = -2146233054          消息=无法加载类型&#39; ConsoleApplication1_ConfigurationEnumerable.PathsConfigSection&#39;从   assembly&#39; System.Configuration,Version = 4.0.0.0,Culture = neutral,   公钥= b03f5f7f11d50a3a&#39 ;.          来源= System.Configuration          类型名= ConsoleApplication1_ConfigurationEnumerable.PathsConfigSection          堆栈跟踪:               在System.Configuration.TypeUtil.GetTypeWithReflectionPermission(IInternalConfigHost)   host,String typeString,Boolean throwOnError)               在System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.Init(RuntimeConfigurationRecord)   configRecord,FactoryRecord factoryRecord)               在System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.InitWithRestrictedPermissions(RuntimeConfigurationRecord)   configRecord,FactoryRecord factoryRecord)               在System.Configuration.RuntimeConfigurationRecord.CreateSectionFactory(FactoryRecord)   factoryRecord)               at System.Configuration.BaseConfigurationRecord.FindAndEnsureFactoryRecord(String   configKey,布尔&amp; isRootDeclaredHere)          的InnerException:

我的错在哪里?

2 个答案:

答案 0 :(得分:4)

configSections标记中指定类时,您需要使用Fully Qualified Assembly Name

<configSections>
  <section name="Disk"
           type="ConsoleApplication1_ConfigurationEnumerable.PathsConfigSection, ConsoleApplication1"/>
</configSections>

这假定程序集的名称为ConsoleApplication1。如果仍然遇到异常,可以使用以下代码确定正确的值:

typeof(ConsoleApplication1_ConfigurationEnumerable.PathsConfigSection).FullName
                                                                      .ToString()

BTW:你的命名空间很奇怪。命名标准建议您在分隔命名空间层次结构时使用点(.):

namespace ConsoleApplication1.ConfigurationEnumerable

答案 1 :(得分:0)

我认为你应该使用第一行(注释掉的那一行)。问题出在配置文件中的<section>元素中。按照丹尼尔的回答看看应该如何看待。