Keeping all your settings in an XML file in a centralized location

Often times you want to centralize some key data, and avoid a DB call

Most of my applications use a settings.xml file where keep all of my settings. I then use a Settings.cs class to view/update those values. It is great for centralizing data while avoiding unnecessary trips to the DB; change once, it's changed everywhere.

One of the most common things I use in my settings class is for my email settings, just in case I want to change the account or smtp that I am using, here is a sample of what one would look like:
<?xml version="1.0" encoding="utf-8" ?>
<settings>
  <smtp>smtp.gmail.com</smtp>
  <ssl>True</ssl>
  <mail_account>demo@naspinski.net</mail_account>
  <mail_password>Iparty</mail_password>
</settings>

Pretty basic stuff there, now here is the Settings.cs class I use to access it using a little Linq-to-XML:
using System.Linq;
using System.Web;
using System.Xml.Linq;

public static class Settings
{
  public static string Get(string setting)
  { // gets the specified setting
    XElement x = XElement.Load(HttpContext.Current.Server.MapPath("~") + "\\App_Data\\settings.xml");
    return (from p in x.Descendants(setting) select p).First().Value;
  }

  public static void Update(string setting, string value)
  { // changes the specified setting
    string file_location = HttpContext.Current.Server.MapPath("~") + "\\App_Data\\settings.xml";
    XElement x = XElement.Load(file_location);
    XElement xe = (from p in x.Descendants(setting) select p).First();
    xe.Value = value;
    x.Save(file_location);
  }
}

As you can see, I keep my settings in the App_Data folder. Here you can see how I use it in some apps, for example, this is how I use it with my Email.cs class:
public Email(string to, string from, string subject, string body) : base(Settings.Get("smtp"), 587)
{
  this.Credentials = new System.Net.NetworkCredential(Settings.Get("mail_account"), Settings.Get("mail_password"));
  ...

I think you can figure out Settings.Update() as it is basically the same. You can use whatever method to encrypt your data whereever you keep it.


Comments (1) -

  • Interesting post.  Do you use any caching for the settings file in order to reduce the IO cost associated with reading out the settings value?
Comments are closed