User765876 User765876 - 3 months ago 29
ASP.NET (C#) Question

How to combine two NameValueCollections?

I have two NameValueCollections:

NameValueCollection customTag = (NameValueCollection)System.Configuration.ConfigurationManager.GetSection("secureAppSettings");
NameValueCollection appSetting = (NameValueCollection)System.Configuration.ConfigurationManager.GetSection("appSettings");


I tried
customTag.Add(appSetting);
method but I get this error:
Collection is read-only.


How would I combine them to one, so i can access all the elements from both?

Answer

To combine the collections, try something like the following:

var secureSettings = (NameValueCollection)System.Configuration.ConfigurationManager.GetSection("secureAppSettings");
var appSettings = (NameValueCollection)System.Configuration.ConfigurationManager.AppSettings;

// Initialise a new NameValueCollection with the contents of the secureAppSettings section
var allSettings = new NameValueCollection(secureSettings);
// Add the values from the appSettings section
foreach (string key in appSettings)
{
    // Overwrite any entry already there
    allSettings[key] = appSettings[key];
}

Use the new allSettings collection to access the combined settings.

Comments