How to save / restore serializable object to / from file?

I have a list of objects and I need to save this somewhere on my computer. I have read several forums, and I know that the object must be Serializable . But it would be nice if I could give an example. For example, if I have the following:

 [Serializable] public class SomeClass { public string someProperty { get; set; } } SomeClass object1 = new SomeClass { someProperty = "someString" }; 

But how can I store object1 somewhere on my computer and retrieve it later?

+82
c # stream serialization
May 24 '11 at 19:22
source share
6 answers

You can use the following:

  /// <summary> /// Serializes an object. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="serializableObject"></param> /// <param name="fileName"></param> public void SerializeObject<T>(T serializableObject, string fileName) { if (serializableObject == null) { return; } try { XmlDocument xmlDocument = new XmlDocument(); XmlSerializer serializer = new XmlSerializer(serializableObject.GetType()); using (MemoryStream stream = new MemoryStream()) { serializer.Serialize(stream, serializableObject); stream.Position = 0; xmlDocument.Load(stream); xmlDocument.Save(fileName); } } catch (Exception ex) { //Log exception here } } /// <summary> /// Deserializes an xml file into an object list /// </summary> /// <typeparam name="T"></typeparam> /// <param name="fileName"></param> /// <returns></returns> public T DeSerializeObject<T>(string fileName) { if (string.IsNullOrEmpty(fileName)) { return default(T); } T objectOut = default(T); try { XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(fileName); string xmlString = xmlDocument.OuterXml; using (StringReader read = new StringReader(xmlString)) { Type outType = typeof(T); XmlSerializer serializer = new XmlSerializer(outType); using (XmlReader reader = new XmlTextReader(read)) { objectOut = (T)serializer.Deserialize(reader); } } } catch (Exception ex) { //Log exception here } return objectOut; } 
+131
May 24 '11 at 19:27
source share

I just wrote a blog post about storing object data in Binary, XML or Json . You are correct that you should decorate your classes with the [Serializable] attribute, but only if you use binary serialization. You can use XML or Json serialization. Here are the functions that can be done in various formats. See My Blog 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 binary 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 binary 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 binary 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 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

This 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 link to the Newtonsoft.Json assembly, which can be obtained from the NuGet Json.NET 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 contents of the variable someClass to a file. WriteToBinaryFile<SomeClass>("C:\someClass.txt", object1); // Read the file contents back into a variable. SomeClass object1= ReadFromBinaryFile<SomeClass>("C:\someClass.txt"); 
+120
Mar 14 '14 at 22:56
source share

You will need to serialize to something: select binary or xml (for serializers by default) or write a special serialization code for serialization into another text form.

Once you have selected this, your serialization (usually) will invoke a stream that writes to some file.

So, with your code, if I were to use XML serialization:

 var path = @"C:\Test\myserializationtest.xml"; using(FileStream fs = new FileStream(path, FileMode.Create)) { XmlSerializer xSer = new XmlSerializer(typeof(SomeClass)); xSer.Serialize(fs, serializableObject); } 

Then for deserialization:

 using(FileStream fs = new FileStream(path, FileMode.Open)) //double check that... { XmlSerializer _xSer = new XmlSerializer(typeof(SomeClass)); var myObject = _xSer.Deserialize(fs); } 

NOTE. This code has not been compiled, let alone run - there may be some errors. In addition, this involves full serialization / deserialization. If you need individual behavior, you will need to do extra work.

+30
May 24 '11 at 19:29
source share

1. Restore an object from a file

From Here you can deserialize an object from a file in two ways.

Solution-1: reading a file into a string and JSON deserialization for type

 string json = File.ReadAllText(@"c:\myObj.json"); MyObject myObj = JsonConvert.DeserializeObject<MyObject>(json); 

Solution-2: deserialize JSON directly from file

 using (StreamReader file = File.OpenText(@"c:\myObj.json")) { JsonSerializer serializer = new JsonSerializer(); MyObject myObj2 = (MyObject)serializer.Deserialize(file, typeof(MyObject)); } 

2. Save the object to a file

from here you can serialize an object to a file in two ways.

Solution-1: Serialize JSON for a string and then write the string to a file

 string json = JsonConvert.SerializeObject(myObj); File.WriteAllText(@"c:\myObj.json", json); 

Solution-2: Serialize JSON directly to a file

 using (StreamWriter file = File.CreateText(@"c:\myObj.json")) { JsonSerializer serializer = new JsonSerializer(); serializer.Serialize(file, myObj); } 

3. Extra

You can download Newtonsoft.Json from NuGet by running the command

 Install-Package Newtonsoft.Json 
+9
Jun 14 '16 at 6:58
source share

** 1. Convert the json string to base64string and write or add it to the binary. 2. Read base64string from the binary and deserialize using BsonReader. **

  public static class BinaryJson { public static string SerializeToBase64String(this object obj) { JsonSerializer jsonSerializer = new JsonSerializer(); MemoryStream objBsonMemoryStream = new MemoryStream(); using (BsonWriter bsonWriterObject = new BsonWriter(objBsonMemoryStream)) { jsonSerializer.Serialize(bsonWriterObject, obj); return Convert.ToBase64String(objBsonMemoryStream.ToArray()); } //return Encoding.ASCII.GetString(objBsonMemoryStream.ToArray()); } public static T DeserializeToObject<T>(this string base64String) { byte[] data = Convert.FromBase64String(base64String); MemoryStream ms = new MemoryStream(data); using (BsonReader reader = new BsonReader(ms)) { JsonSerializer serializer = new JsonSerializer(); return serializer.Deserialize<T>(reader); } } } 
+1
May 26 '18 at 13:24
source share

You can use JsonConvert from the Newtonsoft library. To serialize an object and write to a json file:

 File.WriteAllText(filePath, JsonConvert.SerializeObject(obj)); 

And deserialize it back to the object:

 var obj = JsonConvert.DeserializeObject<ObjType>(File.ReadAllText(filePath)); 
0
Jul 20 '19 at 22:52
source share



All Articles