5,667,575 members and growing! (16,206 online)
Email Password   helpLost your password?
Languages » XML » XML/XSLT     Intermediate

Quick and Dirty Settings Persistence with XML

By circumpunct

A quick and dirty use of an XML file to save program settings between application execution sessions.
XML, C# 2.0, C#Windows, .NET, .NET 2.0, Win2K, WinXPVS2005, Visual Studio, Dev

Posted: 9 Sep 2006
Updated: 9 Sep 2006
Views: 24,645
Bookmarked: 49 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
28 votes for this Article.
Popularity: 7.00 Rating: 4.84 out of 5
0 votes, 0.0%
1
0 votes, 0.0%
2
1 vote, 3.6%
3
2 votes, 7.1%
4
25 votes, 89.3%
5

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:

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:

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:

<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:

<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:

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));
}

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

About the Author

circumpunct


Circumpunct is a Brianist
Location: Saudi Arabia Saudi Arabia

Other popular XML articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 20 of 20 (Total in Forum: 20) (Refresh)FirstPrevNext
GeneralShort and to the pointmemberjoachimj5:07 25 Aug '08  
GeneralImplementation with Typeconverter and Application Relative filenamesmemberphelmers14:03 12 Jul '07  
GeneralFantastic CodememberRascalRobot6:38 17 Apr '07  
GeneralRe: Fantastic Codemembersdenman14:17 17 Apr '07  
GeneralExcellent code buddymembermrsnipey21:48 1 Feb '07  
GeneralFile locationsmemberMinds_Eye11:14 28 Nov '06  
GeneralConfiguration BlockmemberTrance Junkie0:03 12 Sep '06  
GeneralRe: Configuration Blockmembercircumpunct2:39 12 Sep '06  
GeneralRe: Configuration BlockmemberTrance Junkie5:43 12 Sep '06  
GeneralRe: Configuration Blockmembercircumpunct23:18 12 Sep '06  
GeneralTypeConvertermemberdzCepheus11:36 9 Sep '06  
GeneralRe: TypeConvertermemberBat Gurl0:40 10 Sep '06  
GeneralRe: TypeConvertermembercircumpunct23:40 12 Sep '06  
GeneralRe: TypeConvertermemberBat Gurl4:16 19 Sep '06  
QuestionRe: TypeConvertermemberEvis7:49 20 Jan '07  
AnswerRe: TypeConvertermemberJon B.19:19 2 Oct '07  
GeneralUsign datesmemberBat Gurl5:13 9 Sep '06  
GeneralRe: Usign datesmembercircumpunct0:12 10 Sep '06  
GeneralRe: Usign datesmemberBat Gurl0:37 10 Sep '06  
JokeRe: Usign datesmemberMark Farmiloe10:20 22 Feb '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 9 Sep 2006
Editor: Smitha Vijayan
Copyright 2006 by circumpunct
Everything else Copyright © CodeProject, 1999-2008
Web19 | Advertise on the Code Project