sub appsettings in the appsetting node c#

前端 未结 2 387
栀梦
栀梦 2020-12-23 16:41

I am using the app.config file that is created with a console application and I can read the val1 of the key1 using the ConfigurationSettings.AppSettings[\"key1\"].ToS

2条回答
  •  隐瞒了意图╮
    2020-12-23 17:37

    You can add custom sections in app.config without writing additional code. All you have to do is "declaring" new section in configSections node like that

    
          

    and then you can define this section filling it with keys and values:

      
          
          
      
    

    To get value of a key from this section you have to add System.Configuration dll as reference to your project, add using and use GetSection method. Example:

    using System.Collections.Specialized;
    using System.Configuration;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                NameValueCollection test = (NameValueCollection)ConfigurationManager.GetSection("genericAppSettings");
    
                string a = test["another"];
            }
        }
    }
    

    Nice thing is that you can easily make groups of sections if you need this:

    
        
          
    // another sections // another sections

    If you use groups, to access sections you have to access them using {group name}/{section name} format:

    NameValueCollection test = (NameValueCollection)ConfigurationManager.GetSection("customAppSettingsGroup/genericAppSettings");
    

提交回复
热议问题