Search code examples
c#streamfilestream

Passing subsequence of a stream without copying its content into a new instance


Let's assume I have following method:

void Upload(Stream stream)
{
    // uploads the content of the specified stream somewhere
}

And let's further assume I got some binary file f, which contains some data I'd like to upload with the method above. But: It's not the whole file I want to upload. It's only a certain part of f. More precisely the desired data starts at a certain position s >= 0 and ends at a certain position e <= f.Length.

Is there a way to pass a Stream instance, which starts at position s, with the length of e, without copying all bytes between s and e into a new stream instance? I'm asking because there is the possibility, that file f is quite big and I don't want to make assumptions on potentially available RAM.


Solution

  • Please consider using Stream.CanSeek Property, Stream.Position Property, Stream.Seek Method to "access" the certain part of the stream.

    To have a separate Stream instance with appropriate length, it seems it is required to implement a SubStream class — the wrapper which represents sub-stream. The following references can be useful to implement such a wrapper:

    1. How to access part of a FileStream or MemoryStream, Social MSDN.
    2. How to expose a sub section of my stream to a user, Stackoverflow.