c# MemoryStream.Read()总是读取相同的部分



编辑:解决方案在文章底部

我正在尝试我的运气读取二进制文件。由于我不想依赖byte[] AllBytes = File.ReadAllBytes(myPath),因为二进制文件可能相当大,我想在循环中读取相同大小的一小部分(这很适合要读取的文件格式),使用我称之为"缓冲区"的东西。

    public void ReadStream(MemoryStream ContentStream)
    {
        byte[] buffer = new byte[sizePerHour];
        for (int hours = 0; hours < NumberHours; hours++)
        {                
            int t = ContentStream.Read(buffer, 0, sizePerHour);
            SecondsToAdd = BitConverter.ToUInt32(buffer, 0);
           // further processing of my byte[] buffer
        }
    }

我的流包含我想要的所有字节,这是一件好事。当我进入循环时,有几件事停止了工作。我的int t0,虽然我认为ContentStream.Read()会处理从流内到我的字节数组的信息,但事实并非如此。

我尝试了buffer = ContentStream.GetBuffer(),但这导致我的缓冲区包含我所有的流,我想通过使用读取缓冲区来避免这种行为。

在读取之前将流重置到位置0也没有帮助,为我的Stream.Read()指定偏移量也没有帮助,这意味着我丢失了。

谁能告诉我怎么把流的一小部分读成byte[]?也许加上一些代码?

Thanks in advance

编辑:

指向我正确的方向是答案,如果到达流的末端,.Read()返回0。我将代码修改如下:

    public void ReadStream(MemoryStream ContentStream)
    {
        byte[] buffer = new byte[sizePerHour];
        ContentStream.Seek(0, SeekOrigin.Begin); //Added this line
        for (int hours = 0; hours < NumberHours; hours++)
        {                
            int t = ContentStream.Read(buffer, 0, sizePerHour);
            SecondsToAdd = BitConverter.ToUInt32(buffer, 0);
           // further processing of my byte[] buffer
        }
    }

一切都像魔法一样。每次在hour上迭代并给出偏移量时,我最初将流重置为其原点。将"set to begin - part"移到我的外观之外,并将偏移量设置为0。

Read在到达流的末尾时返回0。你确定你的记忆流有你想要的内容吗?我已经尝试了以下操作,它的效果如预期的那样:

// Create the source of the memory stream.
UInt32[] source = {42, 4711};
List<byte> sourceBuffer = new List<byte>();
Array.ForEach(source, v => sourceBuffer.AddRange(BitConverter.GetBytes(v)));
// Read the stream.
using (MemoryStream contentStream = new MemoryStream(sourceBuffer.ToArray()))
{
    byte[] buffer = new byte[sizeof (UInt32)];
    int t;
    do
    {
        t = contentStream.Read(buffer, 0, buffer.Length);
        if (t > 0)
        {
           UInt32 value = BitConverter.ToUInt32(buffer, 0);
        }
    } while (t > 0);
}

最新更新