How can we add list or multiple values for a single key in web.config in asp .net

10,646

Solution 1

Add in web config as comma separated valued like

<add key = "xyz" value="val1, val2, val3"/>

access them as

  string[]  xyzValues = System.Configuration.ConfigurationManager.AppSettings["xyz"].Split(",");

Solution 2

You can use the appsettings tag

<appSettings>
  <add key="xyz" value="val1;val2;val3" />
</appSettings>

C# Code

string[] values = ConfigurationManager.AppSettings["xyz"].Split(';');

Solution 3

You can't do it directly but with a little more coding you may have custom config section in your config files. https://msdn.microsoft.com/en-us/library/2tw134k3.aspx link describes how to do custom config.

Other way could be use a separator in value and define multiple values and then use that values using split function(like other have mentioned)

Solution 4

Define a separator character.

Then, get the application setting by its key and use string.Split to get those multiple values as an array or IEnumerable<string>:

IEnumerable<string> values = ConfigurationManager.AppSettings["xyz"].Split(',');
Share:
10,646
Japneet Singh
Author by

Japneet Singh

Software Engineer

Updated on July 19, 2022

Comments

  • Japneet Singh
    Japneet Singh almost 2 years

    How can we add list or multiple values for a single key in web.config?

    For example: I have key named "xyz" it has a list of values, that is , val1, val2, val3 etc.

    And this can be obtained in my code as other keys are accessible.

  • Rob Vermeulen
    Rob Vermeulen almost 5 years
    Shouldn't it be System.Configuration.ConfigurationManager.AppSettings["xyz"]‌​.Split(","); (with the additional 's')
  • Imad
    Imad almost 5 years
    @RobVermeulen you are right, I will update my answer. That was just a typo and OP got that right through intellisense.