Reputation: 972
Could anyone please explain to me the differences, if any?
I tried to Google it but couldn't find much information. Maybe I didn't use correct keywords.
Any insight would be greatly appreciated.
Upvotes: 9
Views: 7550
Reputation: 4992
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.
Upvotes: 17
Reputation: 9627
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."
Upvotes: 4
Reputation: 176219
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.
Upvotes: 5