User765876 User765876 - 1 year ago 177
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
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download