How to most efficiently skip some number of bytes in any Stream
?
If possible, I'd like to get or throw an EndOfStreamException
when trying to skip past the end of the stream.
I am writing a custom stream Reader
for ISO 9660 primitive data types, and this may involve a lot of skipping in seekable and non-seekable streams, both small numbers (4) and large numbers (2048) of bytes. Therefore I want to implement a Skip(int count)
method that is a bit more efficient than reading and discarding the skipped bytes.
For example, in a seekable stream I might do stream.Position += 4
, but this does not throw an EndOfStreamException
when seeking past the end of the stream, and I don't know how to test for that without reading something. For non-seekable streams, setting Position
is not even an option, but reading and subsequently discarding large numbers of bytes and allocating unused byte arrays seems very wasteful.
CanSeek
and either usingSeek
or read+discard) is pretty much "it". Maybe you could risk reading.Length
in theCanSeek
scenario, but: you should exception-handle that too; I'm not sure thatCanSeek
guarantees aLength
implementation. – Marc Gravell