Click here to Skip to main content
15,895,192 members
Articles / Programming Languages / XML

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 105.2K   677   67  
A quick and dirty use of an XML file to save program settings between application execution sessions.
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;
    }
  }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

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