Question

Do I need a Seek call in this code?

// Assume bytes = byte[] of some bytes
using (var memoryStream = new MemoryStream(bytes))
{
    memoryStream.Seek(0, SeekOrigin.Begin);
    return new BinaryFormatter().Deserialize(memoryStream);
}
Was it helpful?

Solution 2

No, you don't have to. For proving that, you can check the constructor code:

public MemoryStream(byte[] buffer, bool writable)
{
    if (buffer == null) throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
    Contract.EndContractBlock();
    _buffer = buffer;
    _length = _capacity = buffer.Length;
    _writable = writable;
    _exposable = false;
    _origin = 0;
    _isOpen = true;
}

Seek changes _position (in your example to 0), which is not assigned in the constructor, so upon construction of the object Position will have the default long value of 0.

It's a different story though if you perform further operations on the stream that could change its Position before reading from it.

OTHER TIPS

No, there is no need to Seek on stream that was just created.

You need to Seek or set Position is you wrote something to the stream before.

I.e. common question is "how to return MemoryStream with some serialized data" - you need to write data to the stream and than Seek to the beginning of the stream so Read will start from the beginning and not the last position of Write (hence always saying that there nothing left to read). Sample question - Can't create MemoryStream.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top