search
HomeBackend DevelopmentC#.Net Tutorial.Net configuration file - inherit ConfigurationSection to implement custom processing classes to process custom configuration nodes

In addition to using the method of inheriting IConfigurationSectionHandler to define a class for processing custom nodes, you can also achieve the same effect by inheriting the ConfigurationSection class.

First let’s talk about an unspoken rule in the .Net configuration file

When configuring a node, for the parameters you want to store Data can be stored in two ways: one is stored in the attributes of the node, and the other is stored in the text of the node.

Because a node can have many attributes, but only one innertext, needs to be added in the program Differentiating these two forms creates complications. In order to avoid this problem, the configuration file of .net is only stored with attributes instead of innertext.


Next, let’swrite a custom configuration file that conforms to this unspoken rule to facilitate testing:

     

<mailServerGroup provider="www.baidu.com">
    <mailServers>
      <mailServer client="http://blog.csdn.net/lhc1105" address="13232@qq.com" userName="lhc" password="2343254"/>
      <mailServer client="http://blog345.csdn.net/lhc1105" address="132wdfgdsggtaewg32@qq.com" userName="dfshs水田如雅"  password="2334t243的萨芬234254"/>
      <mailServer client="http://blog436.csdn.net/lhc1105" address="132wdgadsfgdtaewg32@qq.com" userName="sdfhdfs水田如雅"  password="23ewrty2343的萨芬234254"/>
      <mailServer client="http://blo345734g.csdn.net/lhc1105" address="132wdgdfagdstaewg32@qq.com" userName="sdfher水田如雅"  password="23erwt43的萨芬234254"/>
    </mailServers>
  </mailServerGroup>

Next, we write the corresponding processing class. Here we write from the inside to the outside:

First is the innermost mailServer:

 /// <summary>
    /// Class MailServerElement:用于映射mailServer节点,这里是实际存储数据的地方;
    /// </summary>
    /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 21:51:57</remarks>
    public sealed class MailServerElement : ConfigurationElement  //配置文件中的配置元素
    {

        /// <summary>
        /// Gets or sets the client.
        /// </summary>
        /// <value>The client.</value>
        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:05:40</remarks>
        [ConfigurationProperty("client", IsKey = true, IsRequired = true)]  //client是必须的key属性,有点儿主键的意思,例如,如果定义多个client相同的节点,循环读取的话就只读取到最后一个值
        public string Client
        {
            get
            {
                return this["client"] as string;
            }
            set
            {
                this["client"] = value;
            }

        }
        /// <summary>
        /// Gets or sets the address.
        /// </summary>
        /// <value>The address.</value>
        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:05:38</remarks>
        [ConfigurationProperty("address")]
        public string Address
        {
            get
            {
                return this["address"] as string;
            }
            set
            {
                this["address"] = value;
            }

        }
        /// <summary>
        /// Gets or sets the name of the user.
        /// </summary>
        /// <value>The name of the user.</value>
        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:05:35</remarks>
        [ConfigurationProperty("userName")]
        public string UserName
        {

            get
            {
                return this["userName"] as string;
            }
            set
            {
                this["userName"] = value;
            }

        }
        /// <summary>
        /// Gets or sets the password.
        /// </summary>
        /// <value>The password.</value>
        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:05:33</remarks>
        [ConfigurationProperty("password")]
        public string Password
        {

            get
            {
                return this["password"] as string;
            }
            set
            {
                this["password"] = value;
            }

        }



    }

Then is mailServers, which is a collection of mailServers:

 /// <summary>
    /// Class MailServerCollection:映射mailServers节点,为一个集合类,另外还包含了很多对节点的操作方法,大部分继承自ConfigurationElementCollection
    /// </summary>
    /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 21:52:00</remarks>
    public sealed class MailServerCollection : ConfigurationElementCollection
    {
        /// <summary>
        /// 获取 <see cref="T:System.Configuration.ConfigurationElementCollection" /> 的类型。
        /// </summary>
        /// <value>The type of the collection.</value>
        /// <returns>此集合的 <see cref="T:System.Configuration.ConfigurationElementCollectionType" />。</returns>
        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:05:08</remarks>
        public override ConfigurationElementCollectionType CollectionType
        {
            get
            {
                return ConfigurationElementCollectionType.BasicMap;
            }
         
        }


        /// <summary>
        /// 当在派生的类中重写时,创建一个新的 <see cref="T:System.Configuration.ConfigurationElement" />。
        /// </summary>
        /// <returns>新的 <see cref="T:System.Configuration.ConfigurationElement" />。</returns>
        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:05:03</remarks>
        protected override ConfigurationElement CreateNewElement()
        {
            return new MailServerElement();
        }

        /// <summary>
        /// 在派生类中重写时获取指定配置元素的元素键。
        /// </summary>
        /// <param name="element">要为其返回键的 <see cref="T:System.Configuration.ConfigurationElement" />。</param>
        /// <returns>一个 <see cref="T:System.Object" />,用作指定 <see cref="T:System.Configuration.ConfigurationElement" /> 的键。</returns>
        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:04:51</remarks>
        protected override object GetElementKey(ConfigurationElement element)
        {
            return (element as MailServerElement).Client;
        }

        /// <summary>
        /// 获取在派生的类中重写时用于标识配置文件中此元素集合的名称。
        /// </summary>
        /// <value>The name of the element.</value>
        /// <returns>集合的名称;否则为空字符串。默认值为空字符串。</returns>
        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 23:41:40</remarks>
        protected override string ElementName
        {
            get
            {
                return "mailServer";
            }
        }


        /// <summary>
        /// 获取集合中的元素数。
        /// </summary>
        /// <value>The count.</value>
        /// <returns>集合中的元素数。</returns>
        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:08:24</remarks>
        public new int Count
        {
            get { return base.Count; }
        }

        /// <summary>
        /// 获取或设置此配置元素的属性、特性或子元素。
        /// </summary>
        /// <param name="index">The index.</param>
        /// <returns>MailServerElement.</returns>
        /// <remarks>Editor:v-liuhch</remarks>
        public MailServerElement this[int index]
        {

            get { return BaseGet(index) as MailServerElement; }
            set
            {
                if (BaseGet(index) != null)
                {
                    BaseRemoveAt(index);
                }
                BaseAdd(index, value);
            }

        }

        /// <summary>
        /// 获取或设置此配置元素的属性、特性或子元素。
        /// </summary>
        /// <param name="Name">The name.</param>
        /// <returns>MailServerElement.</returns>
        /// <remarks>Editor:v-liuhch</remarks>
        new public MailServerElement this[string Name]
        {
            get { return BaseGet(Name) as MailServerElement; }
        }

        /// <summary>
        /// Indexes the of.
        /// </summary>
        /// <param name="element">The element.</param>
        /// <returns>System.Int32.</returns>
        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:24:16</remarks>
        public int IndexOf(MailServerElement element)
        {

            return BaseIndexOf(element);
        }

        /// <summary>
        /// Adds the specified element.
        /// </summary>
        /// <param name="element">The element.</param>
        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:26:06</remarks>
        public void Add(MailServerElement element)
        {
            BaseAdd(element);
        }

        /// <summary>
        /// Removes the specified element.
        /// </summary>
        /// <param name="element">The element.</param>
        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:27:01</remarks>
        public void Remove(MailServerElement element)
        {
            if (BaseIndexOf(element) > 0)
            {
                BaseRemove(element.Client);
            }
        }

        /// <summary>
        /// Removes at.
        /// </summary>
        /// <param name="index">The index.</param>
        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:33:29</remarks>
        public void RemoveAt(int index)
        {
            BaseRemoveAt(index);
        }

        /// <summary>
        /// Removes the specified client.
        /// </summary>
        /// <param name="client">The client.</param>
        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:34:04</remarks>
        public void Remove(string client)
        {
            BaseRemove(client);
        }

        /// <summary>
        /// Clears this instance.
        /// </summary>
        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:34:29</remarks>
        public void Clear()
        {
            BaseClear();
        }
    }

The last is the outermost group:

 /// <summary>
    /// Class MailServerSection 为入口:
    /// </summary>
    /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 21:41:02</remarks>
    public class MailServerSection : ConfigurationSection   //继承配置文件中节
    {
        /// <summary>
        /// Gets the provider.:映射mailServerGroup节点的provider
        /// </summary>
        /// <value>The provider.</value>
        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:05:59</remarks>
        [ConfigurationProperty("provider", IsKey = true)]
        public string provider { get { return this["provider"] as string; } }

        /// <summary>
        /// Gets or sets the mail servers.:映射新添加的节点mailServers节点;这个节点下还包含了若干个mailServer节点,因此它是一个集合类
        /// </summary>
        /// <value>The mail servers.</value>
        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:05:56</remarks>
        [ConfigurationProperty("mailServers", IsDefaultCollection = false)]
        public MailServerCollection MailServers
        {
            get
            {
                return this["mailServers"] as MailServerCollection;
            }
            set
            {
                this["mailServers"] = value;
            }

        }
    }

Similarly, associate processing classes and nodes:

 <section name="mailServerGroup" type="继承ConfigurationSection基类.MailServerSection,继承ConfigurationSection基类"/>   
  </configSections>

Then do a test:

class Program
    {
        static void Main(string[] args)
        {
            Test();

        }

        /// <summary>
        /// Tests this instance.:读取节点值示例
        /// </summary>
        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 23:04:53</remarks>
        private static void Test() {

            MailServerSection mailSection = (MailServerSection)ConfigurationManager.GetSection("mailServerGroup");
            Console.WriteLine("MailServerSection 的provider属性值:"+mailSection.provider);
            foreach (MailServerElement config in mailSection.MailServers)
            {
                Console.WriteLine("----------------------------------");
                Console.WriteLine("client值为:"+config.Client);
                Console.WriteLine("address值为:"+config.Address);
                Console.WriteLine("username值为:"+config.UserName);
                Console.WriteLine("password值为:"+config.Password);
                Console.WriteLine("----------------------------------");
            }

            Console.ReadKey();

        }

    }

Originally I also want to upload a picture of the results, but the Internet speed is slow. Forget it, children who like to play can run the results themselves. . . . .

The above is the .Net configuration file - inherit the ConfigurationSection to implement the custom processing class to process the content of the custom configuration node. For more related content, please pay attention to the PHP Chinese website (www.php.cn )!





Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Relevance of C# .NET: A Look at Current UsageThe Continued Relevance of C# .NET: A Look at Current UsageApr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

From Web to Desktop: The Versatility of C# .NETFrom Web to Desktop: The Versatility of C# .NETApr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# .NET and the Future: Adapting to New TechnologiesC# .NET and the Future: Adapting to New TechnologiesApr 14, 2025 am 12:06 AM

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

Is C# .NET Right for You? Evaluating its ApplicabilityIs C# .NET Right for You? Evaluating its ApplicabilityApr 13, 2025 am 12:03 AM

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

C# Code within .NET: Exploring the Programming ProcessC# Code within .NET: Exploring the Programming ProcessApr 12, 2025 am 12:02 AM

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

C# .NET: Exploring Core Concepts and Programming FundamentalsC# .NET: Exploring Core Concepts and Programming FundamentalsApr 10, 2025 am 09:32 AM

C# is a modern, object-oriented programming language developed by Microsoft and as part of the .NET framework. 1.C# supports object-oriented programming (OOP), including encapsulation, inheritance and polymorphism. 2. Asynchronous programming in C# is implemented through async and await keywords to improve application responsiveness. 3. Use LINQ to process data collections concisely. 4. Common errors include null reference exceptions and index out-of-range exceptions. Debugging skills include using a debugger and exception handling. 5. Performance optimization includes using StringBuilder and avoiding unnecessary packing and unboxing.

Testing C# .NET Applications: Unit, Integration, and End-to-End TestingTesting C# .NET Applications: Unit, Integration, and End-to-End TestingApr 09, 2025 am 12:04 AM

Testing strategies for C#.NET applications include unit testing, integration testing, and end-to-end testing. 1. Unit testing ensures that the minimum unit of the code works independently, using the MSTest, NUnit or xUnit framework. 2. Integrated tests verify the functions of multiple units combined, commonly used simulated data and external services. 3. End-to-end testing simulates the user's complete operation process, and Selenium is usually used for automated testing.

Advanced C# .NET Tutorial: Ace Your Next Senior Developer InterviewAdvanced C# .NET Tutorial: Ace Your Next Senior Developer InterviewApr 08, 2025 am 12:06 AM

Interview with C# senior developer requires mastering core knowledge such as asynchronous programming, LINQ, and internal working principles of .NET frameworks. 1. Asynchronous programming simplifies operations through async and await to improve application responsiveness. 2.LINQ operates data in SQL style and pay attention to performance. 3. The CLR of the NET framework manages memory, and garbage collection needs to be used with caution.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor