如何从WPF中的app.config获取List <string>值集合?

Edw*_*uay 68 c# wpf app-config itemscontrol

下面的示例使用我从代码中获取的BackupDirectories列表填充ItemsControl.

如何更改此设置以便从app.config文件中获取相同的信息?

XAML:

<Window x:Class="TestReadMultipler2343.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Grid Margin="10">
        <Grid.RowDefinitions>
            <RowDefinition Height="30"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="120"/>
            <ColumnDefinition Width="160"/>
        </Grid.ColumnDefinitions>
        <TextBlock 
            Grid.Row="0"
            Grid.Column="0"
            Text="Title:"/>
        <TextBlock 
            Grid.Row="0"
            Grid.Column="1" 
            Text="{Binding Title}"/>
        <TextBlock 
            Grid.Row="1"
            Grid.Column="0"
            Text="Backup Directories:"/>
        <ItemsControl 
            Grid.Row="1"
            Grid.Column="1"
            ItemsSource="{Binding BackupDirectories}"/>
    </Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)

后台代码:

using System.Collections.Generic;
using System.Windows;
using System.Configuration;
using System.ComponentModel;

namespace TestReadMultipler2343
{
    public partial class Window1 : Window, INotifyPropertyChanged
    {

        #region ViewModelProperty: Title
        private string _title;
        public string Title
        {
            get
            {
                return _title;
            }

            set
            {
                _title = value;
                OnPropertyChanged("Title");
            }
        }
        #endregion

        #region ViewModelProperty: BackupDirectories
        private List<string> _backupDirectories = new List<string>();
        public List<string> BackupDirectories
        {
            get
            {
                return _backupDirectories;
            }

            set
            {
                _backupDirectories = value;
                OnPropertyChanged("BackupDirectories");
            }
        }
        #endregion

        public Window1()
        {
            InitializeComponent();
            DataContext = this;

            Title = ConfigurationManager.AppSettings.Get("title");

            GetBackupDirectoriesInternal();
        }

        void GetBackupDirectoriesInternal()
        {
            BackupDirectories.Add(@"C:\test1");
            BackupDirectories.Add(@"C:\test2");
            BackupDirectories.Add(@"C:\test3");
            BackupDirectories.Add(@"C:\test4");
        }

        void GetBackupDirectoriesFromConfig()
        {
            //BackupDirectories = ConfigurationManager.AppSettings.GetValues("backupDirectories");
        }


        #region INotifiedProperty Block
        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;

            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion

    }
}
Run Code Online (Sandbox Code Playgroud)

的app.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="title" value="Backup Tool" />
    <!--<add key="backupDirectories">
      <add value="C:\test1"/>
      <add value="C:\test2"/>
      <add value="C:\test3"/>
      <add value="C:\test4"/>
    </add>-->
  </appSettings>
</configuration>
Run Code Online (Sandbox Code Playgroud)

Ada*_*lph 139

你可以在单个值中用分号分隔它们,例如

App.config中

<add key="paths" value="C:\test1;C:\test2;C:\test3" />
Run Code Online (Sandbox Code Playgroud)

C#

var paths = new List<string>(ConfigurationManager.AppSettings["paths"].Split(new char[] { ';' }));
Run Code Online (Sandbox Code Playgroud)

  • 如果您不需要自定义配置部分的开销,这是一种快速的方法.这足够IMO. (19认同)
  • 这是我的想法...自定义配置部分非常好,非常强大,但对于一个简单的字符串数组可能有点过分. (6认同)
  • 啊.很好的解决方案,但只需要提一下你必须添加System.Configuration作为参考(不能只使用"using")才能访问ConfigurationManager. (6认同)
  • 这是我很长时间以来的方式...今天我转换为配置部分,因为管理我的列表(它是一个加载的插件类列表,可以根据环境而改变)变得凌乱里面有30多个字符串. (2认同)

Ric*_*ber 119

您可以在app.config文件中创建自己的自定义配置部分.有相当一些 教程 身边让你开始.最终,你可能有这样的事情:

<configSections>
    <section name="backupDirectories" type="TestReadMultipler2343.BackupDirectoriesSection, TestReadMultipler2343" />
  </configSections>

<backupDirectories>
   <directory location="C:\test1" />
   <directory location="C:\test2" />
   <directory location="C:\test3" />
</backupDirectories>
Run Code Online (Sandbox Code Playgroud)

为了补充理查德的答案,这是你可以使用他的样本配置的C#:

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; }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以按如下方式访问backupDirectories配置部分:

List<directory> dirs = ConfigurationManager.GetSection("backupDirectories") as List<directory>;
Run Code Online (Sandbox Code Playgroud)

  • 我错过了什么,或者三个教程中没有一个真正告诉你如何获得元素列表? (16认同)

Oha*_*der 31

实际上,BCL实际上是一个非常少知名的类:CommaDelimitedStringCollectionConverter.它可以作为ConfigurationElementCollection(如理查德的答案)和自己解析字符串(如亚当的答案)之间的各种中间立场.

例如,您可以编写以下配置部分:

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

然后你可以有一个看起来像这样的app.config:

<?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>
Run Code Online (Sandbox Code Playgroud)

最后,您的代码将如下所示:

var section = (MySection)ConfigurationManager.GetSection("foo");
foreach (var s in section.MyStrings)
    Console.WriteLine(s); //for example
Run Code Online (Sandbox Code Playgroud)

  • 我不确定你为什么要创建一个自定义部分,但后来限制为一个分隔的字符串; 然而,这是我没见过或不知道的东西.这是一个有趣的想法和有据可查,感谢提供! (4认同)

Squ*_*azz 31

我喜欢Richard Nienaber的答案,但正如Chuu指出的那样,它实际上并没有说明如何完成理查德所指的解决方案.因此,我选择向你提供我最终做到这一点的方式,结束理查德所说的结果.

解决方案

在这种情况下,我正在创建一个问候小部件,需要知道它必须要问哪些选项.这可能是OP问题的一个过度设计的解决方案,因为我也在为未来可能的小部件创建一个容器.

首先,我设置我的收藏来处理不同的问候

public class GreetingWidgetCollection : System.Configuration.ConfigurationElementCollection
{
    public List<IGreeting> All { get { return this.Cast<IGreeting>().ToList(); } }

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

    protected override ConfigurationElement CreateNewElement()
    {
        return new GreetingElement();
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        return ((GreetingElement)element).Greeting;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我们创建了一个真实的问候元素和它的界面

(你可以省略界面,这就是我一直这样做的方式.)

public interface IGreeting
{
    string Greeting { get; set; }
}

public class GreetingElement : System.Configuration.ConfigurationElement, IGreeting
{
    [ConfigurationProperty("greeting", IsRequired = true)]
    public string Greeting
    {
        get { return (string)this["greeting"]; }
        set { this["greeting"] = value; }
    }
}
Run Code Online (Sandbox Code Playgroud)

greetingWidget属性,所以我们的配置理解集合

我们将我们的集合定义GreetingWidgetCollection为,ConfigurationProperty greetingWidget以便我们可以在生成的XML中使用"greetingWidget"作为我们的容器.

public class Widgets : System.Configuration.ConfigurationSection
{
    public static Widgets Widget => ConfigurationManager.GetSection("widgets") as Widgets;

    [ConfigurationProperty("greetingWidget", IsRequired = true)]
    public GreetingWidgetCollection GreetingWidget
    {
        get { return (GreetingWidgetCollection) this["greetingWidget"]; }
        set { this["greetingWidget"] = value; }
    }
}
Run Code Online (Sandbox Code Playgroud)

生成的XML

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <widgets>
       <greetingWidget>
           <add greeting="Hej" />
           <add greeting="Goddag" />
           <add greeting="Hello" />
           ...
           <add greeting="Konnichiwa" />
           <add greeting="Namaskaar" />
       </greetingWidget>
    </widgets>
</configuration>
Run Code Online (Sandbox Code Playgroud)

你会这样称呼它

List<GreetingElement> greetings = Widgets.GreetingWidget.All;
Run Code Online (Sandbox Code Playgroud)


ruf*_*fen 9

有同样的问题,但以不同的方式解决了它.它可能不是最好的解决方案,但它是一个解决方案.

在app.config中:

<add key="errorMailFirst" value="test@test.no"/>
<add key="errorMailSeond" value="krister@tets.no"/>
Run Code Online (Sandbox Code Playgroud)

然后在我的配置包装器类中,我添加了一个搜索键的方法.

        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();
        }
Run Code Online (Sandbox Code Playgroud)

对于阅读此内容的任何人,我同意创建自己的自定义配置部分更干净,更安全,但对于需要快速操作的小型项目,这可能会解决它.


小智 7

在App.config中:

<add key="YOURKEY" value="a,b,c"/>
Run Code Online (Sandbox Code Playgroud)

在C#中:

string[] InFormOfStringArray = ConfigurationManager.AppSettings["YOURKEY"].Split(',').Select(s => s.Trim()).ToArray();
List<string> list = new List<string>(InFormOfStringArray);
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

147227 次

最近记录:

6 年,2 月 前