C# Source Code: Serializing and Deserializing an array of Objects in C#
[
Home
|
Contents
|
Search
|
Reply
| Previous | Next ]
C# Source Code
Serializing and Deserializing an array of Objects in C#
By:
Andrew Baker
Email (spam proof):
Email the originator of this post
Date:
Friday, May 21, 2004
Hits:
2634
Category:
Unspecified
Article:
Serialization is as the name suggests the process of storing an object instance into a line of data or byte. This process is generally used to transfer an instance of a class from one location to another. This can be used either the pass the object between two computers (eg. Remoting) or alternatively to store an object state to file. Deserialization is reverse of serialization. It basically involves taking an array of bytes and converting them back into an instance of a know type (or object). In the sample code below we will see how to serialize and deserialize objects using C#. using System; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; namespace vbUsers.Serialization { ///
/// Demonstrates how to convert an array of objects /// into a byte array (i.e. serialize them). ///
class SerializationDemo { [STAThread] static void Main(string[] args) { SerializeToFile(); DeSerializeFromFile(); Console.ReadLine(); } public static void SerializeToFile() { //Create an array of Andrews HumanToSerialize[] Andrews = new HumanToSerialize[10]; for(int i = 0; i < 10;i++) { Andrews[i] = new HumanToSerialize("Andrews", "Baker", 32 + i); } //Open a file to store the objects in using(FileStream stream = File.Open("temp.dat", FileMode.Create)) { //Serialize the array of Andrews to file BinaryFormatter binFormat = new BinaryFormatter(); binFormat.Serialize(stream, Andrews); } } public static void DeSerializeFromFile() { //Create an empty array of Andrews HumanToSerialize[] Andrews = new HumanToSerialize[10]; //Open the file containing the serialized Andrews FileStream stream = File.Open("temp.dat", FileMode.Open); //Deserialize the array of Andrews from file BinaryFormatter binFormat = new BinaryFormatter(); Andrews = (HumanToSerialize[])binFormat.Deserialize(stream); //Display Andrwes for(int i = 0; i < 10;i++) { Console.WriteLine(Andrews[i].FirstName + " " + Andrews[i].LastName + ". Age: " + Andrews[i].Age); } stream.Close(); } } //An array of these classes will be serialize and deserialized //Mark the class with the Serializable attribute [Serializable] public class HumanToSerialize { public HumanToSerialize() { } public HumanToSerialize(string firstName, string lastName, int age) { FirstName = firstName; LastName = lastName; Age = age; } public string FirstName; public string LastName; public int Age; } }
Terms and Conditions
Support this site
Download a trial version of the best FTP application on the internet