I am trying to find a way to read part of a stream. I have a stream with 40000 bytes and need to read only from position 8000 to 15000, problably something easy but I can't seem to find an easy way to get a stream segment.
If the stream support seeking, you can just skip to the position, otherwise you have to read the stream to get to that position:
if (theStream.CanSeek) {
theStream.Seek(8000, SeekOrigin.Current);
} else {
// read 8000 bytes and throw away
}
// read the 7000 bytes to keep
Since reading a part of the stream should be easy enough, I'm assuming you're actually in need of a new Stream-object that only accesses the given segment of the underlying stream.
ie. you want something like this:
Stream segment = new StreamSegment(underlyingStream, 8000, 7000);
I have such a class, and you can find it here: LVK.IO.PartialStream. It relies on other classes from my class library, in particular LVK.IO.WrapperStream, but you can find it all there, just grab the few files you actually need (if you decide to use them.)
To use it, you have to specify whether your PartialStream object owns the underlying stream. If it does, when you dispose of the PartialStream object, it will also dispose of the underlying stream.
So for the above example:
Stream segment = new PartialStream(underlyingStream, false, 8000, 7000);
assuming it shouldn't own the underlying stream (or pass true
as the second parameter.)
Notes:
- Constructing the above PartialStream object will reposition the underlying stream to the start of that segment (position 8000 in the above example.)
- You should not use the underlying stream while you're using the partial stream object, since there's some internal bookkeeping going on related to the position inside the segment. If you reposition the underlying stream without going through the partial stream, the behavior is undefined.