Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to quickly save/load class instance to file

I have several collections of classes/structs in my app.

The class is just a class with fields

class A
{
  public int somevalue;
  public string someothervalue
}

And my collection

List<A> _myList;

I need to be able to save _myList and load. I just want to save all class fields to file and load. I don't want to spend time writing my own save/load. Are there any tools in .NET to help me. I don't care about the file format.

like image 596
Captain Comic Avatar asked Nov 24 '10 12:11

Captain Comic


4 Answers

I just wrote a blog post on saving an object's data to Binary, XML, or Json; well writing an object or list of objects to a file that is. Here are the functions to do it in the various formats. See my blog post for more details.

Binary

/// <summary>
/// Writes the given object instance to a binary file.
/// <para>Object type (and all child types) must be decorated with the [Serializable] attribute.</para>
/// <para>To prevent a variable from being serialized, decorate it with the [NonSerialized] attribute; cannot be applied to properties.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the XML file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the XML file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToBinaryFile<T>(string filePath, T objectToWrite, bool append = false)
{
    using (Stream stream = File.Open(filePath, append ? FileMode.Append : FileMode.Create))
    {
        var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        binaryFormatter.Serialize(stream, objectToWrite);
    }
}

/// <summary>
/// Reads an object instance from a binary file.
/// </summary>
/// <typeparam name="T">The type of object to read from the XML.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the binary file.</returns>
public static T ReadFromBinaryFile<T>(string filePath)
{
    using (Stream stream = File.Open(filePath, FileMode.Open))
    {
        var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        return (T)binaryFormatter.Deserialize(stream);
    }
}

XML

Requires the System.Xml assembly to be included in your project.

/// <summary>
/// Writes the given object instance to an XML file.
/// <para>Only Public properties and variables will be written to the file. These can be any type though, even other classes.</para>
/// <para>If there are public properties/variables that you do not want written to the file, decorate them with the [XmlIgnore] attribute.</para>
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToXmlFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
{
    TextWriter writer = null;
    try
    {
        var serializer = new XmlSerializer(typeof(T));
        writer = new StreamWriter(filePath, append);
        serializer.Serialize(writer, objectToWrite);
    }
    finally
    {
        if (writer != null)
            writer.Close();
    }
}

/// <summary>
/// Reads an object instance from an XML file.
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object to read from the file.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the XML file.</returns>
public static T ReadFromXmlFile<T>(string filePath) where T : new()
{
    TextReader reader = null;
    try
    {
        var serializer = new XmlSerializer(typeof(T));
        reader = new StreamReader(filePath);
        return (T)serializer.Deserialize(reader);
    }
    finally
    {
        if (reader != null)
            reader.Close();
    }
}

Json

You must include a reference to Newtonsoft.Json assembly, which can be obtained from the Json.NET NuGet Package.

/// <summary>
/// Writes the given object instance to a Json file.
/// <para>Object type must have a parameterless constructor.</para>
/// <para>Only Public properties and variables will be written to the file. These can be any type though, even other classes.</para>
/// <para>If there are public properties/variables that you do not want written to the file, decorate them with the [JsonIgnore] attribute.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToJsonFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
{
    TextWriter writer = null;
    try
    {
        var contentsToWriteToFile = JsonConvert.SerializeObject(objectToWrite);
        writer = new StreamWriter(filePath, append);
        writer.Write(contentsToWriteToFile);
    }
    finally
    {
        if (writer != null)
            writer.Close();
    }
}

/// <summary>
/// Reads an object instance from an Json file.
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object to read from the file.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the Json file.</returns>
public static T ReadFromJsonFile<T>(string filePath) where T : new()
{
    TextReader reader = null;
    try
    {
        reader = new StreamReader(filePath);
        var fileContents = reader.ReadToEnd();
        return JsonConvert.DeserializeObject<T>(fileContents);
    }
    finally
    {
        if (reader != null)
            reader.Close();
    }
}

Example

// Write the list of objects to a file.
WriteToXmlFile<List<A>>("C:\myObjects.txt", _myList);

// Read the list of objects from the file back into a variable.
List<A> _myList = ReadFromXmlFile<List<A>>("C:\myObjects.txt");
like image 188
deadlydog Avatar answered Nov 12 '22 01:11

deadlydog


XMLSerializer isn't hard to use. As long as your objects aren't huge, it's pretty quick. I serialize out some huge objects in a few of my apps. It takes forever and the resulting files are almost 100 megs, but they're editable should I need to tweak some stuff. Plus it doesn't matter if I add fields to my objects. The serialized files of the older version of the object still deserialize properly.. I do the serialization on a separate thread so it doesn't matter how long it takes in my case. The caveat is that your A class has to have a constructor for XMLSerialziation to work.

Here's some working code I use to serialize/deserialize with the error handling ripped out for readibility...

private List<A> Load()
{
    string file = "filepath";
    List<A> listofa = new List<A>();
    XmlSerializer formatter = new XmlSerializer(A.GetType());
    FileStream aFile = new FileStream(file, FileMode.Open);
    byte[] buffer = new byte[aFile.Length];
    aFile.Read(buffer, 0, (int)aFile.Length);
    MemoryStream stream = new MemoryStream(buffer);
    return (List<A>)formatter.Deserialize(stream);
}


private void Save(List<A> listofa)
{
    string path = "filepath";
    FileStream outFile = File.Create(path);
    XmlSerializer formatter = new XmlSerializer(A.GetType());
    formatter.Serialize(outFile, listofa);
}
like image 40
Tim Coker Avatar answered Nov 12 '22 03:11

Tim Coker


Old topic, but I modified Tim Coker's answer above to utilize the using blocks to properly dispose of the stream objects and save only a single class instance at a time:

public static T Load<T>(string FileSpec) {
    XmlSerializer formatter = new XmlSerializer(typeof(T));

    using (FileStream aFile = new FileStream(FileSpec, FileMode.Open)) {
        byte[] buffer = new byte[aFile.Length];
        aFile.Read(buffer, 0, (int)aFile.Length);

        using (MemoryStream stream = new MemoryStream(buffer)) {
            return (T)formatter.Deserialize(stream);
        }
    }
}

public static void Save<T>(T ToSerialize, string FileSpec) {
    Directory.CreateDirectory(FileSpec.Substring(0, FileSpec.LastIndexOf('\\')));
    FileStream outFile = File.Create(FileSpec);
    XmlSerializer formatter = new XmlSerializer(typeof(T));

    formatter.Serialize(outFile, ToSerialize);
}
like image 5
AnthonyOSX Avatar answered Nov 12 '22 02:11

AnthonyOSX


There are many serializers:

Part of .net framework

  • XmlSerializer (standardized format, slow and verbose)
  • BinarySerializer (proprietary format, medium speed, supports cyclic graphs, serializes fields instead of properties => annoying versioning)

3rd party:

  • Json-Serializers (standardized format, text-based, shorter than xml)
  • ProtoBuf-Serializers (standardized format, binary, very fast)

I'd probably use a ProtoBuf Serializer if the file may be binary, and a json serializer if it needs to be plain-text.

like image 4
CodesInChaos Avatar answered Nov 12 '22 01:11

CodesInChaos