How to get a List collection of values from app.config in WPF?

前端 未结 7 1093
执笔经年
执笔经年 2020-11-28 22:42

The following example fills the ItemsControl with a List of BackupDirectories which I get from code.

How can I change this

相关标签:
7条回答
  • 2020-11-28 23:11

    Thank for the question. But I have found my own solution to this problem. At first, I created a method

        public T GetSettingsWithDictionary<T>() where T:new()
        {
            IConfigurationRoot _configurationRoot = new ConfigurationBuilder()
            .AddXmlFile($"{Assembly.GetExecutingAssembly().Location}.config", false, true).Build();
    
            var instance = new T();
            foreach (var property in typeof(T).GetProperties())
            {
                if (property.PropertyType == typeof(Dictionary<string, string>))
                {
                    property.SetValue(instance, _configurationRoot.GetSection(typeof(T).Name).Get<Dictionary<string, string>>());
                    break;
                }
    
            }
            return instance;
        }
    

    Then I used this method to produce an instance of a class

    var connStrs = GetSettingsWithDictionary<AuthMongoConnectionStrings>();
    

    I have the next declaration of class

    public class AuthMongoConnectionStrings
    {
        public Dictionary<string, string> ConnectionStrings { get; set; }
    }
    

    and I store my setting in App.config

    <configuration>    
      <AuthMongoConnectionStrings
      First="first"
      Second="second"
      Third="33" />
    </configuration> 
    
    0 讨论(0)
  • 2020-11-28 23:25

    In App.config:

    <add key="YOURKEY" value="a,b,c"/>
    

    In C#:

    string[] InFormOfStringArray = ConfigurationManager.AppSettings["YOURKEY"].Split(',').Select(s => s.Trim()).ToArray();
    List<string> list = new List<string>(InFormOfStringArray);
    
    0 讨论(0)
  • 2020-11-28 23:26

    You can create your own custom config section in the app.config file. There are quite a few tutorials around to get you started. Ultimately, you could have something like this:

    <configSections>
        <section name="backupDirectories" type="TestReadMultipler2343.BackupDirectoriesSection, TestReadMultipler2343" />
      </configSections>
    
    <backupDirectories>
       <directory location="C:\test1" />
       <directory location="C:\test2" />
       <directory location="C:\test3" />
    </backupDirectories>
    

    To complement Richard's answer, this is the C# you could use with his sample configuration:

    using System.Collections.Generic;
    using System.Configuration;
    using System.Xml;
    
    namespace TestReadMultipler2343
    {
        public class BackupDirectoriesSection : IConfigurationSectionHandler
        {
            public object Create(object parent, object configContext, XmlNode section)
            {
                List<directory> myConfigObject = new List<directory>();
    
                foreach (XmlNode childNode in section.ChildNodes)
                {
                    foreach (XmlAttribute attrib in childNode.Attributes)
                    {
                        myConfigObject.Add(new directory() { location = attrib.Value });
                    }
                }
                return myConfigObject;
            }
        }
    
        public class directory
        {
            public string location { get; set; }
        }
    }
    

    Then you can access the backupDirectories configuration section as follows:

    List<directory> dirs = ConfigurationManager.GetSection("backupDirectories") as List<directory>;
    
    0 讨论(0)
  • 2020-11-28 23:27

    There's actually a very little known class in the BCL for this purpose exactly: CommaDelimitedStringCollectionConverter. It serves as a middle ground of sorts between having a ConfigurationElementCollection (as in Richard's answer) and parsing the string yourself (as in Adam's answer).

    For example, you could write the following configuration section:

    public class MySection : ConfigurationSection
    {
        [ConfigurationProperty("MyStrings")]
        [TypeConverter(typeof(CommaDelimitedStringCollectionConverter))]
        public CommaDelimitedStringCollection MyStrings
        {
            get { return (CommaDelimitedStringCollection)base["MyStrings"]; }
        }
    }
    

    You could then have an app.config that looks like this:

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <configSections>
        <section name="foo" type="ConsoleApplication1.MySection, ConsoleApplication1"/>
      </configSections>
      <foo MyStrings="a,b,c,hello,world"/>
    </configuration>
    

    Finally, your code would look like this:

    var section = (MySection)ConfigurationManager.GetSection("foo");
    foreach (var s in section.MyStrings)
        Console.WriteLine(s); //for example
    
    0 讨论(0)
  • 2020-11-28 23:31

    Had the same problem, but solved it in a different way. It might not be the best solution, but its a solution.

    in app.config:

    <add key="errorMailFirst" value="test@test.no"/>
    <add key="errorMailSeond" value="krister@tets.no"/>
    

    Then in my configuration wrapper class, I add a method to search keys.

            public List<string> SearchKeys(string searchTerm)
            {
                var keys = ConfigurationManager.AppSettings.Keys;
                return keys.Cast<object>()
                           .Where(key => key.ToString().ToLower()
                           .Contains(searchTerm.ToLower()))
                           .Select(key => ConfigurationManager.AppSettings.Get(key.ToString())).ToList();
            }
    

    For anyone reading this, i agree that creating your own custom configuration section is cleaner, and more secure, but for small projects, where you need something quick, this might solve it.

    0 讨论(0)
  • 2020-11-28 23:32

    You could have them semi-colon delimited in a single value, e.g.

    App.config

    <add key="paths" value="C:\test1;C:\test2;C:\test3" />
    

    C#

    var paths = new List<string>(ConfigurationManager.AppSettings["paths"].Split(new char[] { ';' }));
    
    0 讨论(0)
提交回复
热议问题