Store String Array In appSettings?

前端 未结 5 1709
借酒劲吻你
借酒劲吻你 2020-11-29 07:57

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

相关标签:
5条回答
  • 2020-11-29 08:48

    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.

    0 讨论(0)
  • 2020-11-29 08:53

    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>(). 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>>();
    
    0 讨论(0)
  • 2020-11-29 08:55

    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();
    
    0 讨论(0)
  • 2020-11-29 08:55

    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(',');
    
    0 讨论(0)
  • 2020-11-29 08:57

    You could use the AppSettings with a 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's a screenshot (german IDE but it might be helpful anyway)

    enter image description here

    0 讨论(0)
提交回复
热议问题