C# App.Config with array or list like data
63,875
Solution 1
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(',');
Solution 2
You can set the type of a setting in the settings designer to StringCollection
, which allows you to create a list of strings.
You can later access individual values as Properties.Settings.Default.MyCollection[x]
.
In the app.config
file this looks as follows:
<setting name="MyCollection" serializeAs="Xml">
<value>
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<string>Value1</string>
<string>Value2</string>
</ArrayOfString>
</value>
</setting>
Solution 3
In App.config,
<add key="YOURKEY" value="a,b,c"/>
In C#,
STRING ARRAY:
string[] InFormOfStringArray = ConfigurationManager.AppSettings["YOURKEY"].Split(',').Select(s => s.Trim()).ToArray();
LIST :
List<string> list = new List<string>(InFormOfStringArray);
Related videos on Youtube
Author by
John Ryann
Updated on December 17, 2020Comments
-
John Ryann over 3 years
How to have array or list like information in app.config? I want user to be able to put as many IPs as possible (or as needed). My program would just take whatever specified in app.config. How to do this?
<?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <add key="ip" value="x" /> <add key="ip" value="y" /> <add key="ip" value="z" /> </appSettings> </configuration> public string ip = ConfigurationManager.AppSettings["ip"];
-
Jonesopolis about 10 years
-
Thorsten Dittmar about 10 years@Jonesy Or use the hassle-free
StringCollection
settings type... -
Squazz almost 6 yearsPossible duplicate of How to get a List<string> collection of values from app.config in WPF?
-
Squazz almost 6 yearsSee my answer here for a way to create your own configuration section: stackoverflow.com/a/33544322/1955317
-
-
Max Carroll over 8 yearsWhen I try and call the setting using Properties.Settings.MyCollection[x], it says An object reference is required for the non-static field, method, or property? any ideas?
-
Max Carroll over 8 yearsahh got it, something like "StringCollection someRegKeys = new Properties.Settings().RegKeys;"
-
Thorsten Dittmar over 8 yearsAm error in my answer. Must be
Properties.Settings.Default.xyz
. -
stomy about 6 yearsWhy not use
.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
? -
bluedog almost 6 yearsThis is a nicer way to go than using string parsing. In the settings designer, use the '...' on the right of the Values field to edit the collection of strings. It gets converted to XML for you.