C # object serialization and deserialization, as shown in the following code example:
- Using System;
- Using System.Text;
- Using System.Collections.Generic;
- Using System.IO;
- Using System.Runtime.Serialization.Formatters.Binary;
- Class Serializableoperate
- {
- private static void Objectserializable (Object obj, String filePath)
- {
- FileStream fs = null;
- Try
- {
- FS = new FileStream (FilePath, FileMode.Create);
- BinaryFormatter bf = new BinaryFormatter ();
- Bf. Serialize (FS, obj);
- }
- catch (IOException ex)
- {
- Console.WriteLine ("Serialization is an error!") ");
- }
- Finally
- {
- if (fs!= null)
- {
- Fs. Close ();
- }
- }
- }
- Private static Object Objectunserializable (String filePath)
- {
- FileStream fs = null;
- Object obj = null;
- Try
- {
- FS = new FileStream (FilePath, FileMode.OpenOrCreate);
- BinaryFormatter bf = new BinaryFormatter ();
- obj = bf. Deserialize (FS);
- }
- catch (IOException ex)
- {
- Console.WriteLine ("Error during deserialization!") ");
- }
- Finally
- {
- if (fs!= null)
- {
- Fs. Close ();
- }
- }
- return obj;
- }
- static void Main (string[] args)
- {
- list<string> list = new list<string>{
- "John", "Dick", "Harry", "Zhao Liu", "Liu Bei"
- };
- String FilePath = "C:\\log.log";
- Console.WriteLine ("Start serialization of the collection!") Please wait a moment ... ");
- Serializableoperate.objectserializable (list, filePath);
- Console.WriteLine ("Start deserialization collection!") Please wait a moment ... ");
- List = (list<string>) serializableoperate.objectunserializable (FilePath);
- foreach (string str in list)
- {
- Console.WriteLine (str);
- }
- }
- }