簡體   English   中英

C# BinaryWriter/BinaryReader - 讀取器順序與寫入順序不匹配

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

我有一些體素數據,我想使用 BinaryWriter 保存,然后使用 BinaryReader 讀取,但我遇到了一些問題。

當我再次閱讀時,似乎數據的順序不同,因此,我生成的體素塊得到了錯誤的值。 據我了解,您必須按照編寫數據的順序讀取數據,這是我應該做的。
我看過幾個例子,但它們都讓我想到了這個問題。 我不知道我做錯了什么。

我在這里創建了一些測試代碼,首先寫入一個文件,然后立即讀取它,然后檢查加載的值是否與它保存的值匹配。 結果總是不匹配,總是停在同一個地方。

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;
    }
}

非常感謝任何幫助了解問題所在!
謝謝

pos += sizeof(int);

應該

pos += sizeof(byte);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM