Store array of strings in appSettings?

I would like to save a one-dimensional array of strings as a record in my appSettings . I can’t just highlight elements with , or | , because the elements themselves may contain these characters.

I thought of storing the array as JSON and then deserialized it using the JavaScriptSerializer .

Is there a “right” / best way to do this?

(My JSON idea seems like a curious hack)

+20
web-config app-config
May 02 '12 at 17:54
source share
4 answers

You can use AppSettings with System.Collections.Specialized.StringCollection .

 var myStringCollection = Properties.Settings.Default.MyCollection; foreach (String value in myCollection) { // do something } 

Each value is separated by a new line.

Here is a screenshot (German IDE, but it can be useful anyway)

enter image description here

+20
May 02 '12 at 18:10
source share

For integers, I found the following method faster.

First of all, create the appSettings key with integer values ​​separated by commas in your app.config.

 <add key="myIntArray" value="1,2,3,4" /> 

Then split and convert the values ​​to an int array using LINQ

 int[] myIntArray = ConfigurationManager.AppSettings["myIntArray"].Split(',').Select(n => Convert.ToInt32(n)).ToArray(); 
+9
Jan 15 '15 at 10:54
source share

You can also use the custom / Collection configuration section for this purpose. Here is an example:

 <configSections> <section name="configSection" type="YourApp.ConfigSection, YourApp"/> </configSections> <configSection xmlns="urn:YourApp"> <stringItems> <item value="String Value"/> </stringItems> </configSection> 

You can also check out this great Visual Studio add-in , which allows you to graphically create .NET configuration sections and automatically generate all the required code and schema definition (XSD) for them.

+5
May 2 '12 at 18:39
source share

For strings simply, just add the following to your web.config :

 <add key="myStringArray" value="fred,Jim,Alan" /> 

and then you can get the value in the array as follows:

 myArray = ConfigurationManager.AppSettings("myStringArray").Split(",") 
+3
Dec 06 '16 at 2:05
source share



All Articles