Write entries to the file yourself. One simple solution would look like this:
StateInformation[] diskReady = GenerateStateGraph(); BinaryFormatter bf = new BinaryFormatter(); using (Stream file = File.OpenWrite(@"C:\temp\states.dat")) { foreach(StateInformation si in diskReady) using(MemoryStream ms = new MemoryStream()) { bf.Serialize(ms, diskReady); byte[] ser = ms.ToArray(); int len = ser.Length; file.WriteByte((byte) len & 0x000000FF); file.WriteByte((byte) (len & 0x0000FF00) >> 8); file.WriteByte((byte) (len & 0x00FF0000) >> 16); file.WriteByte((byte) (len & 0x7F000000) >> 24); file.Write(ser, 0, len); } }
At the same time, no more memory is required for one memory of StateInformation objects, and for deserialization you read four bytes, create a length, create a buffer of this size, fill it and deserialize.
All of the above can be seriously optimized for speed, memory usage and disk size if you create a more specialized format, but the principle is given above.
source share