Click here to Skip to main content
15,867,453 members
Articles / Programming Languages / XML
Article

Quick and Dirty Settings Persistence with XML

Rate me:
Please Sign up or sign in to vote.
4.97/5 (37 votes)
9 Sep 20062 min read 104.2K   676   67   24
A quick and dirty use of an XML file to save program settings between application execution sessions.

The demo project is just a form that remembers its Top and Left values. I'm sure you've seen a gray form with no controls before, so I've spared you the graphic.

Introduction

Yes, I'm afraid it's yet another class to save application settings in an XML file. Why, when there are so many similar articles here? Well, most of them use classes that are big, and some are huge! Great when you need them, but do we really need to use a DLL built from tens of files and thousands of lines of code just to save a few simple settings? In many cases, no.

Why XML and not INI or Registry?

I shall not get into this as it's well covered elsewhere - but basically, you should be saving your settings in XML these days. (Ideally, this will let you move an entire .NET application, including its settings, to another PC just by copying the application folder.)

The Class

This class is quick and dirty. It has no customised trapping of unexpected errors, is not optimized to the last decimal point, and will probably offend the 'best practice' gurus. But it's small, simple, easy to use, and it works.

This is the entire code:

C#
using System;
using System.Windows.Forms;
using System.Xml;

namespace QuickNDirtyXML
{
  public class Settings
  {
    XmlDocument xmlDocument = new XmlDocument();
    string documentPath = Application.StartupPath + "//settings.xml";

    public  Settings()
    { try {xmlDocument.Load(documentPath);}
      catch {xmlDocument.LoadXml("<settings></settings>");}
    }

    public int GetSetting(string xPath, int defaultValue)
    { return Convert.ToInt16(GetSetting(xPath, Convert.ToString(defaultValue))); }

    public void PutSetting(string xPath, int value)
    { PutSetting(xPath, Convert.ToString(value)); }

    public string GetSetting(string xPath,  string defaultValue)
    { XmlNode xmlNode = xmlDocument.SelectSingleNode("settings/" + xPath );
      if (xmlNode != null) {return xmlNode.InnerText;}
      else { return defaultValue;}
    }

    public void PutSetting(string xPath,  string value)
    { XmlNode xmlNode = xmlDocument.SelectSingleNode("settings/" + xPath);
      if (xmlNode == null) { xmlNode = createMissingNode("settings/" + xPath); }
      xmlNode.InnerText = value;
      xmlDocument.Save(documentPath);
    }

    private XmlNode createMissingNode(string xPath)
    { string[] xPathSections = xPath.Split('/');
      string currentXPath = "";
      XmlNode testNode = null;
      XmlNode currentNode = xmlDocument.SelectSingleNode("settings");
      foreach (string xPathSection in xPathSections)
      { currentXPath += xPathSection;
        testNode = xmlDocument.SelectSingleNode(currentXPath);
        if (testNode == null)
        {
            currentNode.InnerXml += "<" + 
                        xPathSection + "></" + 
                        xPathSection + ">";
        }
        currentNode = xmlDocument.SelectSingleNode(currentXPath);
        currentXPath += "/";
      }
      return currentNode;
    }
  }
}

To use it, just drop the settings.cs file into your project (changing the namespace, if you like). Provide a path to the setting and a default value:

C#
private void Form1_Load(object sender, EventArgs e)
{
  this.Top = settings.GetSetting("Form1/Top", this.Top);
  this.Left = settings.GetSetting("Form1/Left", this.Left);
}
private void Form1_FormClosing(object sender, 
                   FormClosingEventArgs e)
{
  settings.PutSetting("Form1/Top", this.Top);
  settings.PutSetting("Form1/Left", this.Left);
}

This generates an XML file like this:

XML
<settings>
  <Form1>
    <Top>187</Top>
    <Left>256</Left>
  </Form1>
</settings>

Why pass a path rather than a pair of strings? Well, you can go down as many nodes as you like (within reason) and are not limited to just a group and a key, so you can do handy things like this:

XML
<settings>
  <Items>
    <Forms>
      <Form1>
        <Top>187</Top>
        <Left>256</Left>
        <Buttons>
          <Button1>
            <Top>10</Top>
            <Left>40</Left>
          </Button1>
          <Button2>
            <Top>10</Top>
            <Left>80</Left>
          </Button2>
        </Buttons>
      </Form1>
      <Form2>
        <Top>187</Top>
        <Left>256</Left>
      </Form2>
    </Forms>
  </Items>
</settings>

Overloads

The Type of the default value determines which overload is called and consequently the Type of the returned value. The class handles strings natively, and there is an overload for integers:

C#
public int GetSetting(string xPath, int defaultValue)
{
    return Convert.ToInt16(GetSetting(xPath, 
           Convert.ToString(defaultValue)));
}
C#
public void PutSetting(string xPath, int value)
{
    PutSetting(xPath, Convert.ToString(value));
}

You can add other overloads if you need them, following the same structure. (Don't forget to specify the culture for converting dates etc., or you can get inconsistent results if the user changes the ambient culture between reading and writing.)

Let the flaming begin :)

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Saudi Arabia Saudi Arabia
Circumpunct is a Brianist

Comments and Discussions

 
QuestionLicense? Pin
Member 1154175422-May-18 22:58
Member 1154175422-May-18 22:58 
QuestionUse in console application Pin
Member 360451521-Jun-12 4:20
Member 360451521-Jun-12 4:20 
GeneralKISS Pin
Mark Treadwell10-Jan-10 12:34
professionalMark Treadwell10-Jan-10 12:34 
Generalvery good work Pin
Donsw8-May-09 16:37
Donsw8-May-09 16:37 
GeneralShort and to the point Pin
joachimj25-Aug-08 4:07
joachimj25-Aug-08 4:07 
GeneralImplementation with Typeconverter and Application Relative filenames Pin
phelmers12-Jul-07 13:03
phelmers12-Jul-07 13:03 
GeneralFantastic Code Pin
EddieRich17-Apr-07 5:38
EddieRich17-Apr-07 5:38 
GeneralRe: Fantastic Code Pin
sdenman17-Apr-07 13:17
sdenman17-Apr-07 13:17 
GeneralExcellent code buddy Pin
mrsnipey1-Feb-07 20:48
mrsnipey1-Feb-07 20:48 
GeneralFile locations Pin
Minds_Eye28-Nov-06 10:14
Minds_Eye28-Nov-06 10:14 
GeneralConfiguration Block Pin
Trance Junkie11-Sep-06 23:03
Trance Junkie11-Sep-06 23:03 
GeneralRe: Configuration Block Pin
circumpunct12-Sep-06 1:39
circumpunct12-Sep-06 1:39 
GeneralRe: Configuration Block Pin
Trance Junkie12-Sep-06 4:43
Trance Junkie12-Sep-06 4:43 
GeneralRe: Configuration Block Pin
circumpunct12-Sep-06 22:18
circumpunct12-Sep-06 22:18 
GeneralTypeConverter Pin
dzCepheus9-Sep-06 10:36
dzCepheus9-Sep-06 10:36 
GeneralRe: TypeConverter Pin
Bat Gurl9-Sep-06 23:40
Bat Gurl9-Sep-06 23:40 
GeneralRe: TypeConverter Pin
circumpunct12-Sep-06 22:40
circumpunct12-Sep-06 22:40 
GeneralRe: TypeConverter Pin
Bat Gurl19-Sep-06 3:16
Bat Gurl19-Sep-06 3:16 
QuestionRe: TypeConverter Pin
Evis20-Jan-07 6:49
Evis20-Jan-07 6:49 
AnswerRe: TypeConverter Pin
Jon B.2-Oct-07 18:19
Jon B.2-Oct-07 18:19 
GeneralUsign dates Pin
Bat Gurl9-Sep-06 4:13
Bat Gurl9-Sep-06 4:13 
Can u explain a bit more about usign dates pls. Whats the problem i can get from culture?

Bat Gurl (squeak squeak)

GeneralRe: Usign dates Pin
circumpunct9-Sep-06 23:12
circumpunct9-Sep-06 23:12 
GeneralRe: Usign dates Pin
Bat Gurl9-Sep-06 23:37
Bat Gurl9-Sep-06 23:37 
JokeRe: Usign dates Pin
Mark Farmiloe22-Feb-07 9:20
Mark Farmiloe22-Feb-07 9:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.