Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.net config file AppSettings: NameValueCollection vs. KeyValueConfigurationCollection

When accessing the current application's appSettings, I get a NameValueCollection:

NameValueCollection settings =
    ConfigurationManager.AppSettings;

When accessing another application's appSettings, I get a KeyValueConfigurationCollection:

KeyValueConfigurationCollection settings = 
    ConfigurationManager.OpenExeConfiguration(sExe).AppSettings.Settings;

  1. Is there a reason why these two methods (ConfigurationManager.AppSettings and AppSettingsSection.Settings) have similar but different (and incompatible) return types? Maybe I'm using an outdated method in one of the two cases?

  2. Is there an easy way to get the same type in both cases, i.e., to get a NameValueCollection for another application's appSettings or a KeyValueConfigurationCollection for the currently running application's appSettings?


Update: For question 2, I've found the following way to get the configuration of the currently running (non-web) application as a KeyValueConfigurationCollection:

KeyValueConfigurationCollection settings = 
    Configuration.ConfigurationManager.OpenExeConfiguration(Configuration.ConfigurationUserLevel.None).AppSettings.Settings;
like image 313
Heinzi Avatar asked Jan 24 '11 13:01

Heinzi


1 Answers

Both are trying to solve the same problem and they're compatible with the same configuration schema, but the difference resides in the fact that both have evolved in different development times, as you said.

But it's not about you're using outdated versions. Those are different ways of getting the same result. Maybe you can't figure why, but the point is sometimes you need to obtain your configuration from different sources, so make sense having these options.

Answering your second question, you can implement an extension method for both return types converting them to a common type.

For example, if you want NameValueCollection you can implement that:

public static NameValueCollection ToCollection(this KeyValueConfigurationCollection source)
{
       // An iterator to create a NameValueCollection here and return it.
}

Or if you want KeyValueConfigurationCollection, you can do the same, but for returning instances of this type.

Then, when you want AppSettings, you can do ConfigurationManager.AppSettings.ToCollection(); and/or ConfigurationManager.OpenExeConfiguration(sExe).AppSettings.Settings.ToCollection();. Check author's answer edit! This part of my answer is wrong and useless :) Thanks.

In fact, name-value collections are someway outdated because are from .net 1.x days. But it's not obsolete, because this is the way of doing it (for now).

like image 98
Matías Fidemraizer Avatar answered Oct 18 '22 01:10

Matías Fidemraizer