views:

710

answers:

2

How to serialize Multiple Objects of the same Class into a single file and Deserialze into Those objects in c#

+2  A: 

Serialize and deserialize an array of those objects.

Mitch Baker
+3  A: 

Try something like this:

using (FileStream output = 
    new FileStream("C:\\peoplearray.dat", FileMode.CreateNew))
{
    BinaryFormatter bformatter = new BinaryFormatter();
    bformatter.Serialize(output, 
                         new Person[] {
                             new Person{Firstname="Alex"}
                         });
}
using (FileStream input = 
      new FileStream("C:\\peoplearray.dat", FileMode.Open))
{
    BinaryFormatter bformatter = new BinaryFormatter();
    var results = bformatter.Deserialize(input) as Person[];
    foreach (Person p in results)
    {
        Console.WriteLine(p.Firstname);
    }
}

So long as person is [Serializable] this will work

Alex James