Skip to content

Instantly share code, notes, and snippets.

@hmcclungiii
Last active October 12, 2022 05:26
Show Gist options
  • Save hmcclungiii/9656636 to your computer and use it in GitHub Desktop.
Save hmcclungiii/9656636 to your computer and use it in GitHub Desktop.
Code template/model for (de)serializing an object to/from an XML file.
using System;
using System.ComponentModel;
using System.Xml.Schema;
using System.Xml.Serialization;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
namespace XmlFile
{
class FileHandler
{
public static MyObject LoadObjectFile(string filespec)
{
MyObject thisObject = null;
try
{
StreamReader stream = new StreamReader(@filespec);
XmlSerializer serializer = new XmlSerializer(typeof(MyObject));
thisObject = (MyObject)serializer.Deserialize(stream);
stream.Close();
}
catch (Exception)
{
thisObject = new MyObject();
}
return thisObject;
}
public static void SaveObjectFile(MyObject thisObject, string filespec)
{
StreamWriter stream = new StreamWriter(filespec);
XmlSerializer serializer = new XmlSerializer(typeof(MyObject));
serializer.Serialize(stream, thisObject);
stream.Close();
}
}
}
@hmcclungiii
Copy link
Author

Updated to include stream.Close(); in two places, to close the stream. Silly mistake there.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment