Skip to content

Instantly share code, notes, and snippets.

@kasajian
Last active November 17, 2023 13:47
Show Gist options
  • Save kasajian/2a0be5f3f1568f704bc3 to your computer and use it in GitHub Desktop.
Save kasajian/2a0be5f3f1568f704bc3 to your computer and use it in GitHub Desktop.
Store C# class for streaming / serializing .NET objecfts to XML

This class stores and loads .xml files into C# objects. File: Store.cs:

Store.cs

Can be used with no new types. File: notypes_example.cs:

notypes_example.cs

Produces output such as. File: notypes_example.xml

notypes_example.xml

top

string[][] x =
{
new [] { "k1", "v1" },
new [] { "k2", "v2" },
};
Store<string[][]>.Save(@"myobject.xml", x);
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ArrayOfString>
<string>k1</string>
<string>v1</string>
</ArrayOfString>
<ArrayOfString>
<string>k2</string>
<string>v2</string>
</ArrayOfString>
</ArrayOfArrayOfString>
See Mee
(http://www.google.com)
using System.IO;
using System.Xml.Serialization;
//--------------------------------------------------------------------------
// Saves an object to an XML file and Loads an object from an XML file.
//
// Examples -- saves to a file:
// CMyClass myobject;
// myobject = ....
// Store<CMyClass>.Save("myobject.xml", myobject);
//
// Examples -- loads from file:
// CMyClass myobject = Store<CMyClass>.Load("myobject.xml);
//--------------------------------------------------------------------------
public class Store<T>
{
// For use with FileStream, MemoryStream, etc.
public static void Save(Stream stream, T theObject)
{
new XmlSerializer(typeof(T)).Serialize(stream, theObject);
}
// Store the object to the specified file
public static void Save(string filename, T theObject)
{
using (TextWriter stream = new StreamWriter(filename))
new XmlSerializer(typeof(T)).Serialize(stream, theObject);
}
// For use with FileStream, MemoryStream, etc.
public static T Load(Stream stream)
{
return (T)(new XmlSerializer(typeof(T)).Deserialize(stream));
}
// Store the object to the specified file
public static T Load(string filename)
{
using (TextReader stream = new StreamReader(filename))
return (T)(new XmlSerializer(typeof(T)).Deserialize(stream));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment