Csharp/C Sharp by API/System.Runtime.Serialization.Formatters.Binary/BinaryFormatter
BinaryFormatter.Deserialize
<source lang="csharp"> using System; using System.Runtime.Serialization.Formatters.Binary; using System.IO; [Serializable] public class BookRecord {
public String title; public int asin; public BookRecord(String title, int asin) { this.title = title; this.asin = asin; }
} public class DeserializeObject {
public static void Main() { FileStream streamIn = new FileStream(@"book.obj", FileMode.Open); BinaryFormatter bf = new BinaryFormatter(); BookRecord book = (BookRecord)bf.Deserialize(streamIn); streamIn.Close(); Console.Write(book.title + " " + book.asin); }
}
</source>
BinaryFormatter.Serialize
<source lang="csharp"> using System; using System.Runtime.Serialization.Formatters.Binary; using System.IO; [Serializable] public class BookRecord {
public String title; public int asin; public BookRecord(String title, int asin) { this.title = title; this.asin = asin; }
}
public class SerializeObject {
public static void Main() { BookRecord book = new BookRecord("title",123456789); FileStream stream = new FileStream(@"book.obj",FileMode.Create); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(stream, book); stream.Close(); }
}
</source>
new BinaryFormatter()
<source lang="csharp"> using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.IO; using System.Runtime.Serialization.Formatters.Binary; [Serializable] public class SampleCollection<T> : List<T> {
private int _intData; private string _stringData; public SampleCollection(int intData, string stringData) { this._intData = intData; this._stringData = stringData; } public int IntVal { get { return this._intData; } } public string StrVal { get { return this._stringData; } }
} public class TypeSafeSerializer {
private TypeSafeSerializer() { } public static void AddValue<T>(String name, T value, SerializationInfo serInfo) { serInfo.AddValue(name, value); } public static T GetValue<T>(String name, SerializationInfo serInfo) { T retVal = (T)serInfo.GetValue(name, typeof(T)); return retVal; }
} public class MainClass {
public static void Main() { SampleCollection<string> strList = new SampleCollection<string>(111, "Value1"); strList.Add("Val1"); strList.Add("Val2"); MemoryStream stream = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, strList); stream.Seek(0, SeekOrigin.Begin); SampleCollection<string> newList = (SampleCollection<string>)formatter.Deserialize(stream); Console.Out.WriteLine(newList.IntVal); Console.Out.WriteLine(newList.StrVal); foreach (string listValue in newList) Console.Out.WriteLine(listValue); }
}
</source>