简体   繁体   中英

ASP.NET: Reading list of values from web.config

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

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()
}

try this

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

or you can iterate

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM