public void Read(Stream stream) { BinaryReader reader = new BinaryReader(stream); header = new Header(reader); Cell[,] cells = new Cell[header.SizeY, header.SizeX]; for (int i = 0; i < header.SizeX * header.SizeY; i++) { int id = reader.ReadInt32(); Header.CellInfo info = header.GetInfo(id); Cell cell = (Cell)Activator.CreateInstance(info.Type); byte[] buffer = new byte[info.DataLength]; //TODO make better solution for substream (maybe remove version-independent hack?) stream.Read(buffer, 0, buffer.Length); BinaryReader subReader = new BinaryReader(new MemoryStream(buffer)); //To make save version-independend try { cell.Deserialize(subReader); } catch (EndOfStreamException) { Console.WriteLine("Save version mismatch at " + info.Type); } subReader.Close(); cells[i / header.SizeY, i % header.SizeX] = cell; } loadedField = new Field(cells); }
public static void Write(Stream stream) { BinaryWriter writer = new BinaryWriter(stream); Header.Write(writer); foreach (Cell cell in Engine.CurrentField.Cells()) { Header.CellInfo info = Header.CurrentHeader.GetInfo(cell.GetType()); writer.Write(info.Id); long position = stream.Position; cell.Serialize(writer); if (stream.Position != position + info.DataLength) { throw new EndOfStreamException("Somehow cell has managed to write more data than expected"); } } }