May 1, 2008

Use KeyValueConfigurationCollection

AppSettings mapped to

            
            
            
            
Then we write our code the access that seciton. Please note that we are not going to use the ConfigurationSection itself, what we are interested is the property in ConfigurationSetting, which is AppSettingsSection.Settings . Below is the code.
            public class Settings
            {
            private static KeyValueConfigurationCollection keywords;
            private static System.Configuration.Configuration config;
            private static System.Configuration.Configuration Config
            {
            get
            {
            if (config == null)
            {
            config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            }
            return config;
            }
            }

            public static KeyValueConfigurationCollection Keywords
            {
            get
            {
            if (keywords == null)
            {
            AppSettingsSection section = Config.GetSection("Keywords") as AppSettingsSection;
            keywords = section.Settings;
            }
            return keywords;
            }
            }

            public static void Save()
            {
            Config.Save();
            }
            }

            

To use the the settings, we can write the following code.

            Console.WriteLine(Settings.Keywords.Count.ToString());
            Settings.Keywords.Add("type", "html");
            Settings.Save();