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.
Person object, close the file. I don't want to serialize a List<Person> and write it all at once. index parameter): Open the file, seek the index position (based on object length), deserialize the object at index, return the object. index position, go to index position, delete it, save the 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With