按名称查找app.config元素列表

时间:2018-02-20 05:12:27

标签: c# .net configuration app-config

我想根据名称从app.config中检索设置。

  <jobs>
    <add name="Name" sftpName="sftp" jobName="jobName"/>
    <add name="Name2" sftpName="sftp2" jobName="jobName2"/>
  </jobs>

我希望能够按名称查找。

我为作业创建了ConfigurationSection,但我似乎无法根据名称给它提供名称,sftpName和jobName。

这将在之后反序列化为一个类。

在.NET中是否有办法可以自动生成某些内容?

1 个答案:

答案 0 :(得分:1)

实现这一目标的方法是拥有一个集合:

textBox_Number

在.config中添加以下内容:

textBox_Name

简称为:

using System.Configuration;

namespace SerialApp
{
    public class JobSection : ConfigurationSection
    {
        [ConfigurationProperty("jobs", IsDefaultCollection = true)]
        public JobCollection Jobs
        {
            get
            {
                JobCollection hostCollection = (JobCollection)base["jobs"];
                return hostCollection;
            }
        }
    }

    public class JobCollection : ConfigurationElementCollection
    {
        public new JobConfigElement this[string name]
        {
            get
            {
                if (IndexOf(name) < 0) return null;
                return (JobConfigElement)BaseGet(name);
            }
        }
        public JobConfigElement this[int index]
        {
            get { return (JobConfigElement)BaseGet(index); }
        }
        public int IndexOf(string name)
        {
            name = name.ToLower();

            for (int idx = 0; idx < base.Count; idx++)
            {
                if (this[idx].Name.ToLower() == name)
                    return idx;
            }
            return -1;
        }
        public override ConfigurationElementCollectionType CollectionType
        {
            get { return ConfigurationElementCollectionType.BasicMap; }
        }
        protected override ConfigurationElement CreateNewElement()
        {
            return new JobConfigElement();
        }
        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((JobConfigElement)element).Name;
        }
        protected override string ElementName
        {
            get { return "job"; }
        }
    }

    public class JobConfigElement : ConfigurationElement
    {
        public JobConfigElement() { }

        [ConfigurationProperty("name", DefaultValue = "Name")]
        public string Name
        {
            get { return (string)this["name"]; }
            set { this["name"] = value; }
        }
        [ConfigurationProperty("sftpName", DefaultValue = "sftp")]
        public string SftpName
        {
            get { return (string)this["sftpName"]; }
            set { this["sftpName"] = value; }
        }
        [ConfigurationProperty("jobName", DefaultValue = "jobName")]
        public string JobName
        {
            get { return (string)this["jobName"]; }
            set { this["jobName"] = value; }
        }
    }
}