Bryan Fok
Bryan Fok

Reputation: 3487

Why FileStream.Length is long type, but FileStream.Read argument - offset has a shorter length?

Why FileStream.Length is long type, but FileStream.Read argument - offset has a shorter length int instead?

Bryan

Upvotes: 13

Views: 6845

Answers (6)

Stav Bodik
Stav Bodik

Reputation: 2134

FileStream extending Stream,

Stream can handle number of byte[int.MaxValue] arrays and together they have a long length.

But when you use Read, you can read only part of it to a byte array with int.MaxValue.

Think about that if you want to read from disk a file bigger then 2G = int.MaxValue , you will need to read it in chunks of byte[int.MaxValue]

(:

Upvotes: 0

Guffa
Guffa

Reputation: 700352

The offset is the index into the byte array where the data is placed. You can't allocate an array that is larger than 2 GB, so there is no need for a bigger number for the offset.

Upvotes: 6

Sylca
Sylca

Reputation: 2545

FileStream.Length gets the length in bytes of the stream and FileStream.Read reads a block of bytes from the stream. So, logically you'll have more single bytes than blocks of that bytes. I'm assuming that for this reason FileStream.Length requires long type.

Upvotes: 1

Lonli-Lokli
Lonli-Lokli

Reputation: 3766

As addition to mike z answer, why byte[] cannot be indexed more than int.MaxValue - class Array implements IList with object this[int index] { get; set; } method, so index can be only integer.

Upvotes: 2

Mike Zboray
Mike Zboray

Reputation: 40818

I'm assuming you are referring to this method which is overridden from the base class Stream.

The offset is the location in the array argument to place the bytes not the offset from the beginning of the FileStream. The array argument is of type byte[] which cannot have more than int.MaxValue elements.

Upvotes: 1

sisve
sisve

Reputation: 19781

The offset parameter tells where to start writing data in your array, the array parameter. It does not point out an offset in the file data.

The offset parameter gives the offset of the byte in array (the buffer index) at which to begin reading, and the count parameter gives the maximum number of bytes to be read from this stream. The returned value is the actual number of bytes read, or zero if the end of the stream is reached. If the read operation is successful, the current position of the stream is advanced by the number of bytes read. If an exception occurs, the current position of the stream is unchanged.

Source: FileStream.Read

Upvotes: 6

Related Questions