Reputation: 22506
I have to configure a list of values in the web.config of MVC 5 application.
Is there a way to read multiple appSettings
values? For example get all that have some prefix.
<appSettings>
<add key="mylist_1" value="val1" />
<add key="mylist_2" value="val2" />
<add key="mylist_3" value="val3" />
<add key="mylist_4" value="val4" />
<add key="otherlist_1" value="val1" />
<add key="otherlist_2" value="val2" />
<add key="otherlist_3" value="val3" />
<add key="otherlist_4" value="val4" />
</appSettings>
I have to get mylist_1
or otherlist_1
.
The simple option is to put all the values under one key, delimited by some char and split the string in the code.
Upvotes: 1
Views: 717
Reputation: 118947
Using System.Configuration.ConfigurationManager.AppSettings
will give you all of the settings, you can then filter out the ones you need quite easily from the collection.
var keys = ConfigurationManager
.AppSettings
.AllKeys
.Where(k => k.StartsWith("xxx"));
var values = keys
.Select(k => new KeyValuePair<string, string>
(k, ConfigurationManager.AppSettings[k]));
Now you can see all the keys/values like this:
foreach (var kvp in values)
{
var key = kvp.Key;
var val = kvp.Value;
}
Make sure you have a project reference to System.Configuration
and a respective using System.Configuration;
statement.
Upvotes: 3
Reputation: 4344
var mylistValues = ConfigurationManager.AppSettings.AllKeys.Where(p => p.StartsWith("mylist_")).Select(p => ConfigurationManager.AppSettings[p]).ToList();
Upvotes: 1