Store String Array In appSettings?
Asked Answered
W

6

39

I'd like to store a one dimensional string array as an entry in my appSettings. I can't simply separate elements with , or | because the elements themselves could contain those characters.

I was thinking of storing the array as JSON then deserializing it using the JavaScriptSerializer.

Is there a "right" / better way to do this?

(My JSON idea feels kinda hacky)

Weisberg answered 2/5, 2012 at 17:54 Comment(1)
I recommend the Newtonsoft JSON stuff, if you go that route...Shonna
S
27

You could use the AppSettings with a System.Collections.Specialized.StringCollection.

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

Each value is separated by a new line.

Here's a screenshot (german IDE but it might be helpful anyway)

enter image description here

Sedation answered 2/5, 2012 at 18:10 Comment(4)
Can this be used for integers?Ramonramona
@akdurmus: only if you convert them to int: int[] ints = new int[strings.Count]; for(int i = 0; i < strings.Count; i++) ints[i] = int.Parse(strings[i]);Sedation
I seem to find a better answer and posted below. Thank you @TimRamonramona
A typo in the code: myStringCollection vs. myCollection.Cartwell
C
16

ASP.Net Core supports it binding a list of strings or objects.

For strings as mentioned, it is possible to retrieve it through AsEnumerable().

Or a list of objects via Get<List<MyObject>>(). The sample is below.

appsettings.json:

{
 ...
   "my_section": {
     "objs": [
       {
         "id": "2",
         "name": "Object 1"
       },
       {
         "id": "2",
         "name": "Object 2"
       }
     ]
   }
 ...
}

Class to represent the object

public class MyObject
{
    public string Id { get; set; }
    public string Name { get; set; }
}

Code to retrieve from appsettings.json

Configuration.GetSection("my_section:objs").Get<List<MyObject>>();
Caves answered 30/7, 2020 at 14:16 Comment(2)
Thank you! This works for me. Previously tried simply getvalue and it was nullFrazil
This is super helpful @Rodrigo. What would the syntax look like to pick out an object having a specific id? Such as the one having "id":"2" ?Giaour
R
12

For integers I found the following way quicker.

First of all create a 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 into int array by using LINQ

int[] myIntArray =  ConfigurationManager.AppSettings["myIntArray"].Split(',').Select(n => Convert.ToInt32(n)).ToArray();
Ramonramona answered 15/1, 2015 at 10:54 Comment(0)
U
12

For strings it is easy, simply add the following to your web.config file:

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

and then you can retrieve the value into an array as follows:

var myArray = ConfigurationManager.AppSettings["myStringArray"].Split(',');
Uno answered 6/12, 2016 at 14:5 Comment(2)
Did you mean [...] around "MyStringArray", not (...), or am I missing something?Rocketry
It should be var myArray = ConfigurationManager.AppSettings["MyStringArray"].Split(',');Atomics
H
10

This may be what you are looking for:

appsettings storing the key NoLongerMaintained with an array of strings

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "NoLongerMaintained": ["BCD",
    "DDP",
    "DHF",
    "DHW",
    "DSG",
    "DTH",
    "SCH"]
}

Then you may retrieve it as an array string[] using

var NoLongerMaintained = _config.GetSection("NoLongerMaintained").Get<string[]>();
Hanway answered 10/11, 2022 at 23:12 Comment(0)
L
7

You may also consider using custom configuration section/Collection for this purpose. Here is a sample:

<configSections>
    <section name="configSection" type="YourApp.ConfigSection, YourApp"/>
</configSections>

<configSection xmlns="urn:YourApp">
  <stringItems>
    <item value="String Value"/>
  </stringItems>
</configSection>

You can also check on this excellent Visual Studio add-in that allows you to graphically design .NET Configuration Sections and automatically generates all the required code and a schema definition (XSD) for them.

Luis answered 2/5, 2012 at 18:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.