Cambia Research - Supporting the Microsoft .NET Developer Community Supporting the Microsoft .NET Developer Community  

     | Home  | Articles  | Categories  | Coders  | Search  | Submit  | Contact Us    
There are only two kinds of programming languages: those people always bitch about and those nobody uses. --Bjarne Stroustrup

Share Your Knowledge! -- Create and submit your articles the easy way with WebWriter.

Updated:12:55 AM CT Jan 10, 2007
Posted:12:51 AM CT Jan 10, 2007

How Can I Easily Manage an XML Configuration File in .NET?

Using .NET's built-in XML serialization features

Author: Steve Lautenschlager

SnippetDataIOC#.NETXML

 Summary

XML serialization can be very easy in .NET. It is perfect for managing configuration files or small sets of data that don't need a full database solution.

The following code sample can be copied directly into a Visual Studio console project. Create the console project first. Then delete everything in the Class1.cs file replacing it with the code below. Compile and run.

So, the gist of it is this. Create a configuration class that will hold all of your configuration information. Then use .NET's built in XML Serialization features to read and write the XML configuration file.

One thing to watch out for when managing configuration files is versions. You will eventually realize that you wanted to store more variables in your configuration file or perhaps remove some that were there before.

For example, suppose your configuration class has a variable called Var1. Later on you realize you want to add a Var2, but there are already old config files out there that don't have a Var2. .NET will do a pretty good job of reading the XML file anyway and filling the properties it can find. In our example, there will be no value for Var2 in old XML files, so the Var2 property will be whatever it was initialized to.

But .NET may not be able to handle every situation you may face. You may find you need to do some customization, in that case it will be critical that you know the version number of the configuration file so that you can ensure it is parsed correctly. Anyway, versioning is a good practice. I learned the hard way, but you can benefit from my mistakes.

Simple Configuration File Using XML Serialization

using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace Cambia
{
   class MainClass
   {
   [STAThread]
      static void Main(string[] args)
      {
         // Create a new configuration object
         // and initialize some variables
         Configuration c = new Configuration();
         c.StringItem = "My Config";
         c.IntItem = 2456;

         // Serialize the configuration object to a file
         Configuration.Serialize("config.xml", c);

         // Read the configuration object from a file
         Configuration c2 = Configuration.Deserialize("config.xml");

         // Write out the variables read from the file
         Console.WriteLine(c2.StringItem);
         Console.WriteLine(c2.IntItem);

      }
   }

   #region -- Configuration Class --
   /// <summary>
   /// This Configuration class is basically just a set of 
   /// properties with a couple of static methods to manage
   /// the serialization to and deserialization from a
   /// simple XML file.
   /// </summary>
   [Serializable]
   public class Configuration
   {
      int _Version;
      string _StringItem;
      int _IntItem;

      public Configuration()
      {
         _Version = 1;
         _StringItem = "";
         _IntItem = -1;
      }
      public static void Serialize(string file, Configuration c)
      {
         System.Xml.Serialization.XmlSerializer xs 
            = new System.Xml.Serialization.XmlSerializer(c.GetType());
         StreamWriter writer = File.CreateText(file);
         xs.Serialize(writer, c);
         writer.Flush();
         writer.Close();
      }
      public static Configuration Deserialize(string file)
      {
         System.Xml.Serialization.XmlSerializer xs 
            = new System.Xml.Serialization.XmlSerializer(
               typeof(Configuration));
         StreamReader reader = File.OpenText(file);
         Configuration c = (Configuration)xs.Deserialize(reader);
         reader.Close();
         return c;
      }
      public int Version
      {
         get { return _Version; }
         set { _Version = value; }
      }
      public string StringItem
      {
         get { return _StringItem; }
         set { _StringItem = value; }
      }
      public int IntItem
      {
         get { return _IntItem; }
         set { _IntItem = value; }
      }

   }
   #endregion

}

Output from running the above console application

My Config
2456

Here's what the XML configuration file looks like

<Configuration>
   <Version>1</Version>
   <StringItem>My Config</StringItem>
   <IntItem>2456</IntItem>
</Configuration>

Add New Comment
How Can I Easily Manage an XML Configuration File in .NET?
Rick..08 Mar 07, 16:10Reply 
re: How Can I Easily Manage an XML Configuration File in .NET?
Steve Lautenschlager08 Mar 07, 22:15Reply 
re: How Can I Easily Manage an XML Configuration File in .NET?
George25 May 07, 12:18Reply 
How Can I Easily Manage an XML Configuration File in .NET?
Googler128 Aug 07, 16:32Reply 
How Can I Easily Manage an XML Configuration File in .NET?
David18 Oct 07, 9:02Reply 
re: How Can I Easily Manage an XML Configuration File in .NET?
Steve Lautenschlager18 Oct 07, 21:12Reply 
CR Comments by Cambia Research
advertisement
 
Steve Lautenschlager (steve)
Steve is the founder and creator of Cambia Research. Developing and maintaining the site combines his passions for technology, writing and education.
Steve holds a Ph.D. in particle physics from Duke University, has worked at CERN, the European center for particle physics (where the web was born) and in Microsoft's web division with microsoft.com, msnbc.com and other web properties. Steve is a web consultant specializing in Microsoft.NET technologies. Read more here.


 
Copyright © Cambia Research 2002-2007. All Rights Reserved. steve [ at ] cambiaresearch.com