Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Runtime.Serialization;
- using System.Security.Permissions;
- using System.Diagnostics;
- using System.IO;
- using System.Runtime.Serialization.Formatters.Binary;
- class Program
- {
- public static void Main(string[] args)
- {
- Car c1= new Car ();
- Serializer(c1, @"C:\cars.txt");
- Deserializer(@"C:\cars.txt");
- Console.WriteLine(c1.color);
- }
- const int VERSION = 1;
- static void Serializer(Car carItem, string fileName)
- {
- Stream stream = null;
- try
- {
- IFormatter formatter = new BinaryFormatter();
- stream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None);
- formatter.Serialize(stream, VERSION);
- formatter.Serialize(stream, carItem);
- }
- catch
- {
- // do nothing
- }
- {
- if (null != stream)
- stream.Close();
- }
- }
- static Car Deserializer(string fileName)
- {
- Stream stream = null;
- Car carItem = null;
- try
- {
- IFormatter formatter = new BinaryFormatter();
- stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None);
- int version = (int)formatter.Deserialize(stream);
- Debug.Assert(version == VERSION);
- carItem = (Car)formatter.Deserialize(stream);
- }
- catch
- {
- // do nothing
- }
- finally
- {
- if (null != stream)
- stream.Close();
- }
- return carItem;
- }
- }
- [Serializable]
- public class Car {
- public int speed=150;
- public String color="red";
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement