Last active
October 12, 2022 05:26
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated to include stream.Close(); in two places, to close the stream. Silly mistake there.