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.
- For insertion, here’s how it goes: Open/Create File, Seek end of the file, Add a serialized
Personobject, close the file. I don’t want to serialize aList<Person>and write it all at once. - For Reading (based on the
indexparameter): Open the file, seek theindexposition (based on object length), deserialize the object atindex, return the object. - Deletion: just like reading the record at
indexposition, 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:
That will allow the
formatter.Serialize(fs,person)to append itself to the file.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.