How to skip bytes in a stream

What is the most efficient way to skip a certain number of bytes in any Stream ?

If possible, I would like to get or throw an EndOfStreamException when trying to skip the end of the stream.


I am writing a custom Reader stream for primitive ISO 9660 data types, and this can include many omissions in search and non-selectable streams, both small numbers (4) and large numbers (2048) bytes. Therefore, I want to implement the Skip(int count) method, which is slightly more efficient than reading and discarding missed bytes.

For example, in a seekable stream , I could make stream.Position += 4 , but that does not throw an EndOfStreamException when searching at the end of the stream, and I don't know how to check this without reading something. For streams that are not searchable, setting Position is not even an option, but reading and then discarding a large number of bytes and allocating unused byte arrays seems very wasteful.

+6
source share
1 answer

Instead of stream.Position += 4 you can use stream.Seek(4, SeekOrigin.Current); that saves a single call to the Win32 API.

You can always check the Length property of a stream, if supported. If it is not supported, there is no other way than trying to read from the stream. In fact, in threads where the length is unknown, the search is essentially readable.

If CanSeek is false, you cannot read Length and vice versa.

About lost memory while reading, you do not need to read the number of bytes that you skip. You can allocate a fixed memory size (large or small) and use it for any desired length. If you need to skip more than this size, you just read the x / size blocks and read the rest of x % size bytes.

+8
source

Source: https://habr.com/ru/post/922208/


All Articles