Is there anyway to achieve that without loading the whole file into memory? If so, what do you suggest me to do?
Class implementation:
[Serializable()]
public class Car
{
public string Brand { get; set; }
public string Model { get; set; }
}
[Serializable()]
public class CarCollection : List<Car>
{
}
Serialization to file:
CarCollection cars = new CarCollection
{
new Cars{ Brand = "BMW", Model = "7.20" },
new Cars{ Brand = "Mercedes", Model = "CLK" }
};
using (Stream stream = File.Open("data", FileMode.Create))
{
BinaryFormatter bin = new BinaryFormatter();
bin.Serialize(stream, cars);
}
To deserialize the collection one object at a time, you also need to serialize it one at a time.
Simplest way is to define your own generic class:
Then you can simply write:
A slightly more complex case might be if your
CarsCollectionbelongs to a different class. In that case, you will need to implementISerializable, but the principle is similar.On a side note, usual convention is not to name entities in plural (i.e.
Carsshould be namedCar).