How to access a certain group of bytes in a MemoryStream?

I have a MemoryStream that reads some data during a do...while loop, and I need to check the last 5 bytes that have been read.

How can I access the last 5 bytes read in a MemoryStream?

Jon Skeet
people
quotationmark

Just set the position to 5 bytes behind, and reread those bytes:

byte[] GetLast5BytesRead(MemoryStream stream)
{
    // TODO: Validation that stream.Position is at least 5
    byte[] ret = new byte[5];
    stream.Position -= 5;
    // TODO: Consider throwing an exception if this doesn't return 5
    Stream.Read(ret, 0, 5);
    return ret;
}

people

See more on this question at Stackoverflow