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?
NameValueCollection is used to store a collection of associated String keys and String values that can be accessed either with the key or with the index. It is very similar to C# HashTable, HashTable also stores data in Key , value format . NameValueCollection can hold multiple string values under a single key.
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.
I tried
customTag.Add(appSetting);
method but I get this error:Collection is read-only.
This means the customTag
object is read only, and can't be written to. .Add
attempts to modify the original NameValueCollection
. System.Configuration
contains a ReadOnlyNameValueCollection
that extends NameValueCollection
to make it read only, and so despite casting to the generic NameValueCollection
, the object is still read only.
How would I combine them to one, so i can access all the elements from both?
All you need is to add both collections to a third writable NameValueCollection
.
Given:
var customTag = (NameValueCollection)System.Configuration.ConfigurationManager.GetSection("secureAppSettings");
var appSetting = (NameValueCollection)System.Configuration.ConfigurationManager.GetSection("appSettings");
You could .Add
both:
var collection = new NameValueCollection();
collection.Add(customTag);
collection.Add(appSettings);
However, the NameValueCollection
constructor has a shorthand that calls Add
internally:
var collection = new NameValueCollection(customTag);
collection.Add(appSettings);
Be aware, that in both cases, using Add
will allow multiple values to be added to each key.
For example, if you were to merge {foo: "bar"}
and {foo: "baz"}
the result would be {foo: ["bar", "baz"]}
(JSON syntax used for brevity).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With