Advertisement
Guest User

Serialization

a guest
Mar 25th, 2017
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.00 KB | None | 0 0
  1. using System;
  2. using System.Runtime.Serialization;
  3. using System.Security.Permissions;
  4. using System.Diagnostics;
  5. using System.IO;
  6. using System.Runtime.Serialization.Formatters.Binary;
  7.  
  8.  
  9.  
  10. class Program
  11.     {
  12.         public static void Main(string[] args)
  13.         {
  14.          
  15.             Car c1= new Car ();
  16.             Serializer(c1, @"C:\cars.txt");
  17.             Deserializer(@"C:\cars.txt");
  18.             Console.WriteLine(c1.color);
  19.            
  20.         }
  21.        
  22.         const int VERSION = 1;
  23.         static void Serializer(Car carItem, string fileName)
  24.         {
  25.             Stream stream = null;
  26.             try
  27.             {
  28.                 IFormatter formatter = new BinaryFormatter();
  29.                 stream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None);
  30.                 formatter.Serialize(stream, VERSION);
  31.                 formatter.Serialize(stream, carItem);
  32.             }
  33.             catch
  34.             {
  35.                 // do nothing
  36.             }
  37.             {
  38.                 if (null != stream)
  39.                     stream.Close();
  40.             }
  41.         }
  42.  
  43.         static Car Deserializer(string fileName)
  44.         {
  45.             Stream stream = null;
  46.             Car carItem = null;
  47.             try
  48.             {
  49.                 IFormatter formatter = new BinaryFormatter();
  50.                 stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None);
  51.                 int version = (int)formatter.Deserialize(stream);
  52.                 Debug.Assert(version == VERSION);
  53.                 carItem = (Car)formatter.Deserialize(stream);
  54.             }
  55.             catch
  56.             {
  57.                 // do nothing
  58.             }
  59.             finally
  60.             {
  61.                 if (null != stream)
  62.                    stream.Close();
  63.             }
  64.             return carItem;
  65.         }
  66.        
  67.        
  68.     }
  69.     [Serializable]
  70.     public class Car {
  71.     public int speed=150;
  72.     public String color="red";
  73.    
  74.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement