Kamyar
Kamyar

Reputation: 18797

Using BinaryFormatter in a sequential manner in C#

Note: I'm aware about the disadvantages of using BinaryFormatter in large files. But this is a homework for my friend:

(.Net Framework 4)I have created a simple Person class which should be serialized and written in a binary file.

I'm not sure if using the BinaryFormatter is the right way to do this. e.g for insert, I've seen examples like:

FileStream fs = new FileStream(_fileName, FileMode.Open);
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fs, person);
fs.Close();  

which causes all the data in file to be lost and the file will only contain the person object. How can I do the Binary read/write/delete of objects in a sequential way in a file? My guess for insertion was to use another stream, serialize the object into that stream. write the stream to a byte array and use that byte array to write to the end of my main file stream. But I couldn't think of a suitable way for insert/delete operations. Any better suited approach to use instead of BinaryFormatter?

Note: To be more clear, he told me the teacher wants them to calculate the amount of time for each operation.
Thank you.

Upvotes: 3

Views: 4197

Answers (1)

NominSim
NominSim

Reputation: 8511

Your code is correct except for the first line:

FileStream fs = new FileStream(_fileName, FileMode.Append)

That will allow the formatter.Serialize(fs,person) to append itself to the file.

var listFromFile = new List<Person>();    

using (var fileStream = new FileStream("C:\file.dat", FileMode.Open))
{
    var bFormatter = new BinaryFormatter();
    while (fileStream.Position != fileStream.Length)
    {
         list.Add((Person)bFormatter.Deserialize(fileStream));
    }
}

That should work to get the list from the file, as far as insertion goes...you may have to rewrite the objects after you read them with the new object inserted, same with deletion.

Upvotes: 2

Related Questions