How to Get a List<String> Collection of Values from App.Config in Wpf

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

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>;

C# App.Config with array or list like data

The easiest way would be a comma separated list in your App.config file. Of course you can write your own configuration section, but what is the point of doing that if it is just an array of strings, keep it simple.

<configuration>
<appSettings>
<add key="ips" value="z,x,d,e" />
</appSettings>
</configuration>

public string[] ipArray = ConfigurationManager.AppSettings["ips"].Split(',');

wpf - Get values from App Config file

If you expand the Properties section of Visual Studio and double click the settings section, you will be able to add custom settings which end up like so in the config file:

<configuration>
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="WpfApplication1.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<userSettings>
<WpfApplication1.Properties.Settings>
<setting name="FilePath" serializeAs="String">
<value>Thing</value>
</setting>
</WpfApplication1.Properties.Settings>
</userSettings>
</configuration>

Which you can then do this in your code:

string thing = Properties.Settings.Default.FilePath;

Which is nice because it gives you type safety too

How to extract a list from appsettings.json in .net core

You can use the Configuration binder to get a strong type representation of the configuration sources.

This is an example from a test that I wrote before, hope it helps:

    [Fact]
public void BindList()
{
var input = new Dictionary<string, string>
{
{"StringList:0", "val0"},
{"StringList:1", "val1"},
{"StringList:2", "val2"},
{"StringList:x", "valx"}
};

var configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddInMemoryCollection(input);
var config = configurationBuilder.Build();

var list = new List<string>();
config.GetSection("StringList").Bind(list);

Assert.Equal(4, list.Count);

Assert.Equal("val0", list[0]);
Assert.Equal("val1", list[1]);
Assert.Equal("val2", list[2]);
Assert.Equal("valx", list[3]);
}

The important part is the call to Bind.

The test and more examples are on GitHub

Can't use values from App.config file in WPF

You may want to read this:

ConfigurationManager.AppSettings in returning null

You could also try to get the setting by index:

private void Window_Loaded_1(object sender, RoutedEventArgs e)
{
LabelSourcepath.Content = System.Configuration.ConfigurationManager.AppSettings[0];
}

How to get all the values from appsettings key which starts with specific name and pass this to any array?

I'd use a little LINQ:

string[] repositoryUrls = ConfigurationManager.AppSettings.AllKeys
.Where(key => key.StartsWith("Service1URL"))
.Select(key => ConfigurationManager.AppSettings[key])
.ToArray();

How to read values from 'WPF' project App.config file from within class library

You can do the following thing:
if you need to get value from key="key1" just write this(supposing your app.config is in the correct directory).

string str=System.Configuration.ConfigurationSettings.AppSettings["key1"];

Get value in app.config

To solve your issue, you can write your own MarkupExtension.

I prepared a short sample code for you. First of all let's see the MarkupExtension class that retrive the app.Config's appSettings:

namespace WpfApplication1
{
public class AppSettingsExtension : MarkupExtension
{
private string key;

public AppSettingsExtension()
{
}

public AppSettingsExtension(string key)
{
Key = key;
}

public string Key
{
get
{
return key;
}
set
{
key = value;
}
}

public override object ProvideValue(IServiceProvider serviceProvider)
{
return ConfigurationManager.AppSettings[Key];
}
}
}

Now it is possible to use the AppSettingsExtension in a XAML (not inside a <sys:String /> node, since it already returns a string object):

<Window x:Class="WpfApplication1.MainWindow" Name="win"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
xmlns:io="clr-namespace:System.IO;assembly=mscorlib"
Title="MainWindow" Height="350" Width="400">

<Window.Resources>
<local:AppSettings Key="SourceWindow" x:Key="str" />

<ObjectDataProvider x:Key="keyFiles" MethodName="GetFiles" ObjectType="{x:Type io:Directory}">
<ObjectDataProvider.MethodParameters>
<local:AppSettings Key="SourceWindow" />
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>

<StackPanel>
<Label Content="{StaticResource str}" Margin="4" />
<ItemsControl ItemsSource="{Binding Source={StaticResource keyFiles}}" />
</StackPanel>

</Window>

I hope my sample can help you.

Get multiple instances of the same key within custom section

keys have to be by definition unqiue.

"I have to store mail recipients in the app.config. Each section has it's own list of MailTo and CC entries and the section name dictates which group to send the mail out to."

Then you do not have a bunch of key/mail pairs.

You have a bunch of key/mail[] pairs.

For each key, you have a collection of values. So you use a collection of values. To wich the answer would be this: https://stackoverflow.com/a/1779453/3346583

Of course in that case, scaleability might be a problem. But if you need scaleabiltiy, you propably should solve that as a 1:N relationship in a database/XML File/other data structure anyway. Rather then app.onfig entries.



Related Topics



Leave a reply



Submit