65.9K
CodeProject is changing. Read more.
Home

Simple settings using Generics and XML serialization

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.41/5 (9 votes)

Aug 23, 2007

CPOL

1 min read

viewsIcon

28568

downloadIcon

54

An easy and very dynamic way of saving your settings.

Introduction

Very often, when coding an application, you need to store your settings that you can easily load when the program starts. I guess most people use the app.config or settings, but I don't think using those is the best solution. Therefore, I came up with this very easy to use class that enables you to store any type of class to an XML file that can be reloaded very easily.

Using the code

The XmlSettings class uses XML serialization, a very basic and extremely fast method. The Load method takes XMLPath as an argument, and returns our type.

The Save method also takes the XMLpath argument and the T settings argument. T settings is the type you want to be serialized.

public static T Load(string XMLPath)
{
     //Load settings and return our type

     T temp;
     XmlSerializer DeSerializer = new XmlSerializer(typeof(T));
     TextReader reader = new StreamReader(XMLPath);
     temp = (T)DeSerializer.Deserialize(reader);
     reader.Close();
     return temp;
}

public static void Save(string XMLPath, T settings)
{
     //Save settings to xml using our type
     
     XmlSerializer serializer = new XmlSerializer(typeof(T));
     TextWriter writer = new StreamWriter(XMLPath);
     serializer.Serialize(writer, settings);
     writer.Close();
}

Using the XMLSettings class is very basic.

When you want to save settings, first create your settings class with the variables you need in your program. Make sure it has a parameterless constructer. Give it the path to your XML file, and make sure all folders are created. Then, pass your settings class as well.

//Save
XMLSettings<MySettings>.Save(XMLPath, Settings);

When loading, the Load method simply returns your type. Just pass the XML path to the method, and voila!

//Load
setting = XMLSettings<MySettings>.Load(XMLPath);