.NET Compact Framework App.Config Workaround

By Robbe D. Morris

Printer Friendly Version

Robbe Morris
Robbe & Melisa Morris
The current release of the .NET Compact Framework (comes with Visual Studio .NET 2003) does not offer the built in capability to access the App.Config settings file like a .NET Windows Form application does.  If you want to get the same functionality, simply load the config file into an XmlDocument and transpose the xml document into a NameValueCollection.  From there, you can reference the AppSettings collection to retrieve the value by key name.  Let's review the code sample below.
It is important to note that you'll need to include App.Config in your project and set the Properties of the file to be considered Content.  This ensures that your file gets included with deployment.  You'll also only want to call the static method LoadConfig() once when your application loads.


Sample App.Config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <appSettings>
      <add key="Item1" value="value of item 1" />
      <add key="Item2" value="value of item 2" />
      <add key="Item3" value="value of item 3" />
   </appSettings>
</configuration>
		 
Sample Code
using System;
using System.Collections.Specialized; 
using System.Xml;
using System.IO;
 
public class ConfigurationSettings
{

  public static NameValueCollection AppSettings;
 
  public static void LoadConfig()
  { 
    try
    {
 
        string AppPath = Path.GetDirectoryName( Assembly.GetExecutingAssembly().GetName().CodeBase);
        string ConfigFile = Path.Combine(AppPath,"App.config");

        if(File.Exists(ConfigFile) == false)
        {
          System.Windows.Forms.MessageBox.Show("Config file does not exist");
          Application.Exit(); 
          return;
        }
				 
        XmlDocument oXml = new XmlDocument();

        oXml.Load(ConfigFile);
				
        XmlNodeList oList =  oXml.GetElementsByTagName("appSettings"); 

        AppSettings = new NameValueCollection();

        foreach(XmlNode oNode in oList)
        {
           foreach(XmlNode oKey in oNode.ChildNodes)
           {
              AppSettings.Add(oKey.Attributes["key"].Value, oKey.Attributes["value"].Value);
           }
        }

        System.Windows.Forms.MessageBox.Show(ConfigurationSettings.AppSettings["Item1"]);  
 
    }
    catch (Exception) { throw; }
  }

}

Robbe has been a Microsoft MVP in C# since 2004.  He is also the co-founder of NullSkull.com which provides .NET articles, book reviews, software reviews, and software download and purchase advice.