When trying to save custom settings/options for your application I've never liked the user and application settings found using the VB or C#. I wanted to be able to bind my object to a property grid and allow a user to change properties and then write that object back as an XML file. I also wanted to be able to add/remove properties from the class without it causing scheme problems.
using System;
using System.IO;
using System.Xml.Serialization;
public class ObjectSerialization
{
public static void WriteObjectToXML(T oObject, string sPath)
{
// Create a new XmlSerializer instance with the type of the test class
XmlSerializer SerializerObj = new XmlSerializer(typeof(T));
using (TextWriter oWriteFileStream = new StreamWriter(sPath))
{
// Create a new file stream to write the serialized object to a file
SerializerObj.Serialize(oWriteFileStream, oObject);
}
}
public static T ReadXMLToObject(string sPath)
{
if (File.Exists(sPath))
{
// Create a new XmlSerializer instance with the type of the test class
XmlSerializer SerializerObj = new XmlSerializer(typeof(T));
// Create a new file stream for reading the XML file
using (FileStream oReadFileStream = new FileStream(sPath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
// Load the object saved above by using the Deserialize function
return (T)SerializerObj.Deserialize(oReadFileStream);
}
}
else
{
throw new FileNotFoundException("File '" + sPath + "' does not exist.");
}
}
}
//
// Example Usage
//
namespace MyApp
{
[XmlRoot("GeneralSettings")]
class GeneralSettings
{
private const string CONST_Filename = "Settings_General.xml";
public GeneralSettings()
{
this.AutoSave = false;
this.LastUpdated = null;
this.DefaultAuthor = "TalkDotNet";
}
[XmlElementAttribute("AutoSave")]
public bool AutoSave { get; set; }
[XmlElementAttribute("LastUpdated")]
public datetime? LastUpdated { get; set; }
[XmlElementAttribute("DefaultAuthor")]
public string DefaultAuthor { get; set; }
public static GeneralSettings LoadSettings()
{
string sPath = Path.Combine(@"C:\TalkDotNet\MySettings", CONST_Filename);
if (System.IO.File.Exists(sPath))
{
return ObjectSerialization.ReadXMLToObject<GeneralSettings>(sPath);
}
else
{
return new GeneralSettings();
}
}
public void SaveSettings()
{
string sPath = System.IO.Path.Combine(@"C:\AppPath\MySettings", CONST_Filename);
ObjectSerialization.WriteObjectToXML<GeneralSettings>(this, sPath);
}
}
}