Search code examples
c#binaryreaderbinarywriter

C# BinaryWriter/BinaryReader - Reader order doesn't match write order


I have some voxel data I would like to save using BinaryWriter and then read using BinaryReader but I'm encountering some issues.

When I read it again, it seems like the data is in a different order and thus, my resulting voxel chunks get the wrong values. As I understood it you have to read the data in the order you wrote it, which I should be doing.
I've looked at several examples but and they all lead me to this issue. I don't know what I'm doing wrong.

I created some test code here to first write to a file and then read it right afterward and then check to see if the loaded values match the values it saveD. The result is always that it doesn't match and it always stops at the same place.

Block[] blocksToSave = chunk.blocks.GetBlocks();

using (BinaryWriter writer = new BinaryWriter(File.Open(Application.persistentDataPath + "/test.bin", FileMode.OpenOrCreate)))
{
    for (int i = 0; i < blocksToSave.Length; i++)
    {
        writer.Write(blocksToSave[i].id); // The ID is just a byte value.
    }
}

byte[] loadedBlocks = new byte[Chunk.CHUNK_SIZE * Chunk.CHUNK_SIZE * Chunk.CHUNK_SIZE]; // 16 * 16 * 16
using (BinaryReader reader = new BinaryReader(File.Open(Application.persistentDataPath + "/test.bin", FileMode.Open)))
{
    int pos = 0;
    int index = 0;
    int streamLength = (int)reader.BaseStream.Length;

    while (pos < streamLength)
    {
        byte id = reader.ReadByte();
        loadedBlocks[index] = id;
        pos += sizeof(int);
        index++;
    }
}

if (blocksToSave.Length != loadedBlocks.Length)
{
    Debug.LogError("Sizes does not match!");
    return;
}

for (int i = 0; i < blocksToSave.Length; i++)
{
    if (blocksToSave[i].id != loadedBlocks[i])
    {
        Debug.LogError("Expected " + blocksToSave[i].id + " but got " + loadedBlocks[i] + " at index " + i + ".");
        return;
    }
}

Any help to understand what the issue is greatly appreciated!
Thanks


Solution

  • pos += sizeof(int);

    should be

    pos += sizeof(byte);