Kenzo
Kenzo

Reputation: 1837

What does "Position in a stream" mean in C#?

I have trouble to understand the word "Position of a stream". My question is somehow related to the concept of the stream method Seek(); it is kind confusing to me what this method does, they say its purpose is to set the position of the stream to a given value but yet its name describes the seek operation not set operation. Does anyone understand clearly what these two words are for and how they work together? Thanx

Upvotes: 2

Views: 4411

Answers (5)

vr_driver
vr_driver

Reputation: 2085

Also, for the record with NAudio, this used to be stream.GetPosition() as well. It's since changed to just stream.Position

Upvotes: 0

Oded
Oded

Reputation: 499132

A stream is basically a sequence of bytes - the position is the point in the sequence that the stream is in.

The point of Seek is to "jump" to a location in the stream - a specific index (aka Position), similar to seeks done in a hard drive. With Seek you can specify an offset to start seeking from, so how many bytes to "jump".

Upvotes: 2

Peter Kelly
Peter Kelly

Reputation: 14401

I actually agree that, at first glance, Seek is not the best name for what it does. SeekAndSet or SeekAndMove would make more sense to me because that is what the method does - it seeks the position you want in the stream and sets the cursor to that position.

However, when you think of Seek in Computer Science terms in relation to hard disk drives it becomes obvious what this method does. It seeks and moves to the position.

Upvotes: 0

Henk Holterman
Henk Holterman

Reputation: 273419

The following 2 statements do exactly the same:

s.Position = 100;
s.Seek(100, SeekOrigin.Begin);

And they both determine the position (as a bytecount) where the next Read or Write will occur.

The Seek() name is very ancient.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1502006

Think about a file as a sequence of bytes, and a stream as a view over that sequence, with a cursor marking the current position - so as you read data, the cursor is advanced. The Position property is simply the position of that cursor. So when you open a stream it's typically at 0, and as you read it increases. For seekable streams, you can "rewind" to the start of the stream with

stream.Position = 0;

or maybe skip 10 bytes using:

stream.Position += 10;

etc.

Upvotes: 5

Related Questions