How to save/restore serializable object to/from file in C# ?

Using binary file

  • Writes and reads ALL object properties and variables to / from the file (i.e. public, protected, internal, and private).
  • The data saved to the file is not human readable, and thus cannot be edited outside of your application.
  • Have to decorate class (and all classes that it contains) with a**[Serializable]** attribute.
  • Use the**[NonSerialized]** attribute to exclude a variable from being written to the file; there is no way to prevent an auto-property from being serialized besides making it use a backing variable and putting the [NonSerialized] attribute on that.
 1/// <summary>
 2/// Functions for performing common binary Serialization operations.
 3/// <para>All properties and variables will be serialized.</para>
 4/// <para>Object type (and all child types) must be decorated with the [Serializable] attribute.</para>
 5/// <para>To prevent a variable from being serialized, decorate it with the [NonSerialized] attribute; cannot be applied to properties.</para>
 6/// </summary>
 7 
 8/// <summary>
 9/// Writes the given object instance to a binary file.
10/// <para>Object type (and all child types) must be decorated with the [Serializable] attribute.</para>
11/// <para>To prevent a variable from being serialized, decorate it with the [NonSerialized] attribute; cannot be applied to properties.</para>
12/// </summary>
13/// <typeparam name="T">The type of object being written to the XML file.</typeparam>
14/// <param name="filePath">The file path to write the object instance to.</param>
15/// <param name="objectToWrite">The object instance to write to the XML file.</param>
16/// <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>
17public static void WriteToBinaryFile<T>(string filePath, T objectToWrite, bool append = false)
18{
19    using (Stream stream = File.Open(filePath, append ? FileMode.Append : FileMode.Create))
20    {
21        var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
22        binaryFormatter.Serialize(stream, objectToWrite);
23    }
24}
25
26/// <summary>
27/// Reads an object instance from a binary file.
28/// </summary>
29/// <typeparam name="T">The type of object to read from the XML.</typeparam>
30/// <param name="filePath">The file path to read the object instance from.</param>
31/// <returns>Returns a new instance of the object read from the binary file.</returns>
32public static T ReadFromBinaryFile<T>(string filePath)
33{
34    using (Stream stream = File.Open(filePath, FileMode.Open))
35    {
36        var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
37        return (T)binaryFormatter.Deserialize(stream);
38    }
39}
40 

Using XML file

  • Only writes and reads the Public properties and variables to / from the file.
  • Classes to be serialized must contain a public parameterless constructor.
  • The data saved to the file is human readable, so it can easily be edited outside of your application.
  • Use the [XmlIgnore] attribute to exclude a public property or variable from being written to the file.
 1/// <summary>
 2/// Functions for performing common XML Serialization operations.
 3/// <para>Only public properties and variables will be serialized.</para>
 4/// <para>Use the [XmlIgnore] attribute to prevent a property/variable from being serialized.</para>
 5/// <para>Object to be serialized must have a parameterless constructor.</para>
 6/// </summary>
 7 
 8/// <summary>
 9/// Writes the given object instance to an XML file.
10/// <para>Only Public properties and variables will be written to the file. These can be any type though, even other classes.</para>
11/// <para>If there are public properties/variables that you do not want written to the file, decorate them with the [XmlIgnore] attribute.</para>
12/// <para>Object type must have a parameterless constructor.</para>
13/// </summary>
14/// <typeparam name="T">The type of object being written to the file.</typeparam>
15/// <param name="filePath">The file path to write the object instance to.</param>
16/// <param name="objectToWrite">The object instance to write to the file.</param>
17/// <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>
18public static void WriteToXmlFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
19{
20    TextWriter writer = null;
21    try
22    {
23        var serializer = new XmlSerializer(typeof(T));
24        writer = new StreamWriter(filePath, append);
25        serializer.Serialize(writer, objectToWrite);
26    }
27    finally
28    {
29        if (writer != null)
30            writer.Close();
31    }
32}
33
34/// <summary>
35/// Reads an object instance from an XML file.
36/// <para>Object type must have a parameterless constructor.</para>
37/// </summary>
38/// <typeparam name="T">The type of object to read from the file.</typeparam>
39/// <param name="filePath">The file path to read the object instance from.</param>
40/// <returns>Returns a new instance of the object read from the XML file.</returns>
41public static T ReadFromXmlFile<T>(string filePath) where T : new()
42{
43    TextReader reader = null;
44    try
45    {
46        var serializer = new XmlSerializer(typeof(T));
47        reader = new StreamReader(filePath);
48        return (T)serializer.Deserialize(reader);
49    }
50    finally
51    {
52        if (reader != null)
53            reader.Close();
54    }
55}

Using Json

Add this NuGet package :

  • Only writes and reads the Public properties and variables to / from the file.
  • Classes to be serialized must contain a public parameterless constructor.
  • The data saved to the file is human readable, so it can easily be edited outside of your application.
  • Use the [JsonIgnore] attribute to exclude a public property or variable from being written to the file.
 1/// <summary>
 2/// Writes the given object instance to a Json file.
 3/// <para>Object type must have a parameterless constructor.</para>
 4/// <para>Only Public properties and variables will be written to the file. These can be any type though, even other classes.</para>
 5/// <para>If there are public properties/variables that you do not want written to the file, decorate them with the [JsonIgnore] attribute.</para>
 6/// </summary>
 7
 8/// <typeparam name="T">The type of object being written to the file.</typeparam>
 9/// <param name="filePath">The file path to write the object instance to.</param>
10/// <param name="objectToWrite">The object instance to write to the file.</param>
11/// <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>
12public static void WriteToJsonFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
13{
14    TextWriter writer = null;
15    try
16    {
17        var contentsToWriteToFile = Newtonsoft.Json.JsonConvert.SerializeObject(objectToWrite);
18        writer = new StreamWriter(filePath, append);
19        writer.Write(contentsToWriteToFile);
20    }
21    finally
22    {
23        if (writer != null)
24            writer.Close();
25    }
26}
27
28/// <summary>
29/// Reads an object instance from an Json file.
30/// <para>Object type must have a parameterless constructor.</para>
31/// </summary>
32/// <typeparam name="T">The type of object to read from the file.</typeparam>
33/// <param name="filePath">The file path to read the object instance from.</param>
34/// <returns>Returns a new instance of the object read from the Json file.</returns>
35public static T ReadFromJsonFile<T>(string filePath) where T : new()
36{
37    TextReader reader = null;
38    try
39    {
40        reader = new StreamReader(filePath);
41        var fileContents = reader.ReadToEnd();
42        return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(fileContents);
43    }
44    finally
45    {
46        if (reader != null)
47            reader.Close();
48    }
49}

Have to decorate class (and all classes that it contains) with a [Serializable] attribute. Use the [NonSerialized] attribute to exclude a variable from being written to the file; there is no way to prevent an auto-property from being serialized besides making it use a backing variable and putting the [NonSerialized] attribute on that.

1// Write the contents of the variable someClass to a file.
2WriteToXXXXFile<SomeClass>("C:\someClass.txt", object1);
3
4// Read the file contents back into a variable.
5SomeClass object1= ReadFromXXXXXFile<SomeClass>("C:\someClass.txt");

Test Code

 1
 2[System.Serializable]
 3public class Identify
 4{
 5    public string PageName;
 6    public List<string> Css = new List<string>();
 7    public List<string> Name = new List<string>();
 8    public List<string> LinkText = new List<string>();
 9    public List<string> Id = new List<string>();
10    public List<string> XPath = new List<string>();
11}
12
13List<Identify> identifyList = new List<Identify>();
14Identify Item1 = new Identify();
15Item1.Id.Add("Aid01");
16Item1.Id.Add("Aid02");
17Item1.Css.Add("Acss01");
18Item1.Css.Add("Acss02");
19Item1.Name.Add("AName01");
20Item1.Name.Add("AName02");
21Item1.Name.Add("AName03");
22Item1.PageName = "AMyPageName";
23Item1.XPath.Add("AXPath1");
24Item1.XPath.Add("AXPath2");
25Item1.XPath.Add("AXPath3");
26Item1.LinkText.Add("ALinkText1");
27Item1.LinkText.Add("ALinkText2");
28Item1.LinkText.Add("ALinkText3");
29identifyList.Add(Item1);
30
31Identify Item2 = new Identify();
32Item2.Id.Add("Bid01");
33Item2.Id.Add("Bid02");
34Item2.Name.Add("BName01");
35Item2.Name.Add("BName02");
36Item2.Name.Add("BName03");
37Item2.PageName = "BMyPageName";
38Item2.XPath.Add("BXPath1");
39Item2.XPath.Add("BXPath2");
40Item2.XPath.Add("BXPath3");
41Item2.LinkText.Add("BLinkText1");
42Item2.LinkText.Add("BLinkText2");
43Item2.LinkText.Add("BLinkText3");
44identifyList.Add(Item2);
45
46Serializer.WriteToXmlFile("c:\\tmp\\duo.xml", identifyList, false);
47Serializer.WriteToBinaryFile("c:\\tmp\\duo.bin", identifyList, false);
48Serializer.WriteToJsonFile("c:\\tmp\\duo.json", identifyList, false);

Results :

Source :

https://blog.danskingdom.com/saving-and-loading-a-c-objects-data-to-an-xml-json-or-binary-file/