Alex
Alex

Reputation: 65

How to truncate a FileStream to read just specific bytes?

How to truncate a FileStream to read just specific bytes. As example: I would like that the FileStream delivers next 100 bytes from position 10.

My code:

    public System.IO.Stream GetFileStream()
    {
        FileStream fs = File.OpenRead(filePath);
        fs.Seek(10, SeekOrigin.Begin); //setting start position

        //How to set the length or the end position of the stream here?

        return fs;
    }

   private void TestFileCopy()
    {
        FileStream fs = GetFileStream();
        FileStream fsCopy = File.OpenWrite(filePathCopy);

        fs.CopyTo(fsCopy);
    }

I am able to set the start position but can not find out how to say the stream to stop after some bytes.
In the TestFileCopy Method I just want to copy the stream, without any data of the position and the length.
In the GetFileStream Method I want that the stream delivers bytes from position A to B.
Thanks

Upvotes: 1

Views: 517

Answers (1)

Peter Duniho
Peter Duniho

Reputation: 70652

If you want an actual Stream instance which represents exactly the desired bytes and no more, then you either need to write your own wrapper (I've implemented a "SubsetStream" class at least a couple of times over the years…it's not too hard), or you can just read the bytes you want, copying them into a MemoryStream and then returning that MemoryStream as the Stream instance for whatever code actually needs it.

Of course if you don't literally need a Stream instance, then simply keeping track of the total bytes remaining to read so that you know when to stop reading should not be too hard. Something like:

int bytesLeft = ...; // initialized to whatever

while (bytesLeft > 0)
{
    int bytesRead = fs.Read(rgb, 0, Math.Min(rgb.Length, bytesLeft));

    bytesLeft -= bytesRead;
}

In your example, you seem to have complete control over both the code that reads the input stream and the code that writes the output. So you should be able to change it so that it doesn't need a Stream as input for the output, and you just write the bytes as they are immediately read from the input.

Upvotes: 2

Related Questions