FANDOM


Store C# class for streaming / serializing .NET objecfts to XML

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));
    }
     
}

Can be used with no new types:Edit

            string[][] x = 
            {
                new [] { "k1", "v1" },
                new [] { "k2", "v2" },
            };

            Store<string[][]>.Save(@"myobject.xml", x);

ProducesEdit

<?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>

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.