Streams Why Use Seek(0L, SeekOrigin.Begin) instead of Position = 0 or vice versa

stream.Seek(x, SeekOrigin.Begin); and stream.Position = x; both result in the stream position being set to x. The difference is that the Position setter unconditionally discards any read buffer, while the Seek method attempts to retain the part of the buffer that is still relevant to the new position.

You'll have to test, which one is faster for your scenario, but there's definitely a performance difference and neither is faster in all cases. I really wonder why this difference isn't documented.


In your example there is no difference.

The actual difference between Stream.Position and Stream.Seek is that Position uses an absolute offset whereas Seek uses an offset relative to the origin specified by the second argument.


As far as I can tell, at least for this specific case, nothing.

Both method Seek() and property Position require CanSeek to be true so from what I see it's up to the implementer.

Seek is really there to allow searching from specified locations (SeekOrigins) to an offset (the examples given on MSDN are somewhat convoluted but representative of the purpose: http://msdn.microsoft.com/en-us/library/system.io.filestream.seek.aspx).

Position is absolute and is obviously not meant for searching.

The case you mentioned just happens to be equivalent.

Personally, I'd use .Position = 0 to move to the beginning of the stream as that reads cleaner to me than "Seek using the beginning of the file as an origin and move this 0 offset of bytes."

Tags:

C#

Asp.Net