WordPress Hosting
Free Photos
WordPress Themes

[HowTo] Serialize any class into binary

//// How to make any class serializable in binary mode // Example class [Serializable()] public class Example : ISerializable { public string Name; public int Age; public Example() { Name = "Example name"; Age = 69; } #region Serialization public X3D(SerializationInfo info, StreamingContext ctxt) { Name = (string)info.GetValue("name", typeof(string)); Age = (int)info.GetValue("age", typeof(int)); } public void GetObjectData(SerializationInfo info, StreamingContext ctxt) { info.AddValue("name", Name); info.AddValue("age", Age); } #endregion } // To serialize: void Serialize(Example example, string path) { Stream stream = File.Open(path, FileMode.Create); BinaryFormatter bformatter = new BinaryFormatter(); bformatter.Serialize(stream, example); stream.Close(); } // To deserialize Example Deserialize(string path) { Stream stream = File.Open(path, FileMode.Open); BinaryFormatter bformatter = new BinaryFormatter(); Example example = (Example)bformatter.Deserialize(stream); stream.Close(); return example; }
A simple how-to example about how to serialize any custom class into a binary file, and loading it back

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.