1

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.

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1
 var mylistValues =  ConfigurationManager.AppSettings.AllKeys.Where(p => p.StartsWith("mylist_")).Select(p => ConfigurationManager.AppSettings[p]).ToList();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.