Shawn Miller

.NET Compact Framework ConfigurationManager

May 02, 200612:37 AM

The .NET Compact Framework doesn't have a ConfigurationManager class like the full .NET 2.0 Framework.  On the full .NET Framework you gain access to application settings through the static System.Configuration.ConfigurationManager.AppSettings member.

We've created a basic ConfigurationManager class for the .NET Compact Framework similar to the one provided by the full .NET Framework.  It provides the basic read functionality into the "appSettings" section of an XML based configuration file similar to the one listed below.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <appSettings>
     
<add key="EmailAddress" value=user@domain.com />
     
<add key="Password" value="bigboy" />
     
<add key="DeviceId" value="12345678-90ab-cdef-ghij-klmnopqrstuv" />
     
<add key="UpdateFrequency" value="15000" />
  
</appSettings>
</configuration>

We made the location of our XML based configuration file identical to the full .NET Framework's App.config naming convention.  Which means, if your executable assembly is named "MyApplication.exe" you'll need a "MyApplication.exe.config" file in the application's startup path.  You can accomplish this easily in Visual Studio 2005 by adding the "MyApplication.exe.config" XML file to your solution, setting its "Build Action" property to "Content", and setting its "Copy to Output Directory" property to "Copy Always".  Better yet, you could name your XML file "App.config" and create a post-build action to rename the file appropriately and copy it to the correct location (this would be roughly equivilant to the App.config build sequence of the full .NET Framework).

In addtion to reading these key/value pairs we also needed a way to change the values and have those changes saved back to the configuration file.  In the interest of time we decided to add a Save method to the ConfigurationManager class.  The more correct approach would be to implement functionality similar to the excellent strongly typed and user/application scoped constructs in the System.Configuration namespace; possibly eventually deriving some classes from ApplicationSettingsBase.  However, that's a bit more work than we wanted to tackle.  It's our opinion the lack of any configuration features in the .NET Compact Framework can only mean that they're on their way in a future release or service pack.  We'll leave the rest up to Microsoft.  For now, here's our .NET Compact Framework version of ConfigurationManager:

using System;

using System.IO;

using System.Xml;

using System.Reflection;

using System.Collections.Specialized;

 

namespace FreshLogicStudios.Atlas.Mobile.PocketPC

{

    /// <summary>

    /// Provides access to configuration files for client applications on the .NET Compact Framework.

    /// </summary>

    public static class ConfigurationManager

    {

        #region Private Members

       

        private static NameValueCollection appSettings = new NameValueCollection();

        private static string configFile;

 

        #endregion

 

        #region Public Properties

 

        /// <summary>

        /// Gets configuration settings in the appSettings section.

        /// </summary>

        public static NameValueCollection AppSettings

        {

            get

            {

                return appSettings;

            }

        }

 

        #endregion

 

        #region Constructors

 

        /// <summary>

        /// Static constructor.

        /// </summary>

        static ConfigurationManager()

        {

            // Determine the location of the config file

            ConfigurationManager.configFile = String.Format("{0}.config", System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);

 

            // Ensure configuration file exists

            if (!File.Exists(ConfigurationManager.configFile))

            {

                throw new FileNotFoundException(String.Format("Configuration file ({0}) could not be found.", ConfigurationManager.configFile));

            }

           

            // Load config file as an XmlDocument

            XmlDocument myXmlDocument = new XmlDocument();

            myXmlDocument.Load(ConfigurationManager.configFile);

 

            // Add keys and values to the AppSettings NameValueCollection

            foreach(XmlNode appSettingNode in myXmlDocument.SelectNodes("/configuration/appSettings/add"))

            {

                ConfigurationManager.AppSettings.Add(appSettingNode.Attributes["key"].Value, appSettingNode.Attributes["value"].Value);

            }

        }

 

        #endregion

 

        #region Public Methods

 

        /// <summary>

        /// Saves changes made to the configuration settings.

        /// </summary>

        public static void Save()

        {

            // Load config file as an XmlDocument

            XmlDocument myXmlDocument = new XmlDocument();

            myXmlDocument.Load(ConfigurationManager.configFile);

 

            // Get the appSettings node

            XmlNode appSettingsNode = myXmlDocument.SelectSingleNode("/configuration/appSettings");

 

            if (appSettingsNode != null)

            {

                // Remove all previous appSetting nodes

                appSettingsNode.RemoveAll();

 

                foreach(string key in AppSettings.AllKeys)

                {

                    // Create a new appSetting node

                    XmlElement appSettingNode = myXmlDocument.CreateElement("add");

                   

                    // Create the key attribute and assign its value

                    XmlAttribute keyAttribute = myXmlDocument.CreateAttribute("key");

                    keyAttribute.Value = key;

 

                    // Create the value attribute and assign its value

                    XmlAttribute valueAttribute = myXmlDocument.CreateAttribute("value");

                    valueAttribute.Value = AppSettings[key];

 

                    // Append the key and value attribute to the appSetting node

                    appSettingNode.Attributes.Append(keyAttribute);

                    appSettingNode.Attributes.Append(valueAttribute);

 

                    // Append the appSetting node to the appSettings node

                    appSettingsNode.AppendChild(appSettingNode);

                }

            }

           

            // Save config file

            myXmlDocument.Save(ConfigurationManager.configFile);

        }

 

        #endregion

    }

}