Home > other >  ASP.NET: Reading list of values from web.config
ASP.NET: Reading list of values from web.config

Time:12-31

in a cs file I have a IF function like this>

If (myValue == 'AA' || myValue == 'BB' || myValue == 'CC')
{
DoThis()
}

But now and then I have to add some more conditions: myValue == 'DD' and so on.

Is not possible insert the new values (and All values) in the web.config and read from there instead of modify the code?

For example, in my web.config file I can have something like this:

<appSettings>
     <add key="AA" value="AA"/>
     <add key="BB" value="BB"/>
     <add key="CC" value="CC"/>
     <add key="DD" value="DD"/>
</appSettings> 

and in the code I should have something like:

IF mySearchString is present in the list from web.config, THEN call DoThis() method

Thank you in advance.

Luis

CodePudding user response:

First create a key in web.config with comma separated value as below.

<appSettings>
     <add key="Categories" value="AA,BB,CC,DD"/>
</appSettings>

Then access the variable and split it.

var categories = System.Configuration.ConfigurationManager.AppSettings["Categories"].Split(',');
        
if(categories.Contains(myValue)){
    DoThis()
}

CodePudding user response:

try this

var appSets = 
ConfigurationManager.GetSection("appSettings") as NameValueCollection;
   
  if (appSets["AA"]=="AA" || appSets["BB"]=="BB") do something
    

or you can iterate using Linq or foreach

    foreach (var item in appSets.Keys)
    {
      var key = item.ToString();
      var value = appSets[key];
    }
  • Related