Skip to content

Instantly share code, notes, and snippets.

@lski
Created December 28, 2014 17:25
Show Gist options
  • Save lski/0b1804f2ae1dd5caf24f to your computer and use it in GitHub Desktop.
Save lski/0b1804f2ae1dd5caf24f to your computer and use it in GitHub Desktop.
Offers simple static functions for exporting and importing an object to xml from and into a file
/// <summary>
/// Offers simple static functions for exporting and importing an object to xml from and into a file
/// </summary>
public static class Objects {
/// <summary>
/// Exports passed object to the file stated using a DataContractSerialiser to convert it into XML. REQUIRED A serializable attribute type recongnised by DataContractSerializer
/// E.g. Serializable, XmlSerializable, and DataContract
/// </summary>
/// <param name="filename">The file to export to</param>
/// <remarks></remarks>
public static void ExportToFile<T>(string filename, T obj) {
var file = new FileInfo(filename);
// 1. If the file exists the directory must also exist, so delete the file ready for the new one
// 2. Ensure the directory exists, before attempting to write a new settings file
if (file.Exists) {
file.Delete();
}
else {
file.Directory.Create();
}
var xmlSettings = new XmlWriterSettings {
Indent = true,
CloseOutput = true
};
using (var fs = File.Create(file.FullName)) {
using (var writer = XmlWriter.Create(fs, xmlSettings)) {
var serializer = new DataContractSerializer(obj.GetType());
serializer.WriteObject(writer, obj);
}
}
}
/// <summary>
/// Imports an object from a file in an XML format that was created using ExportToFile
/// </summary>
/// <param name="filename">The file to import from.</param>
/// <exception cref="FileNotFoundException">If the file to read from, simply does not exist.</exception>
/// <exception cref="XmlException">If the file is a malformed xml document</exception>
/// <remarks></remarks>
public static T ImportFromFile<T>(string filename) {
var xmlSettings = new XmlReaderSettings {
IgnoreWhitespace = true,
CloseInput = true
};
using (var reader = XmlReader.Create(filename, xmlSettings)) {
// Get the type of this object so that we can create a blank instance of the object
var serializer = new DataContractSerializer(typeof(T));
var obj = (T)serializer.ReadObject(reader);
return obj;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment