Search code examples
c#.netiostreambytestream

How to read all bytes of a stream but the last 8


I have the following code:

using (var fs = new FileStream(@"C:\dump.bin", FileMode.Create))
{
    income.CopyTo(fs);
}

income is a stream that I need to save to disk, the problem is that I want to ignore the last 8 bytes and save everything before that. The income stream is read only, forward only so I cannot predict its size and I don't want to load all the stream in memory due to huge files being sent.

Any help will be appreciated.


Solution

  • Maybe (or rather probably) there is a cleaner way of doing it but being pragmatic at the moment the first thought which comes to my mind is this:

    using (var fs = new FileStream(@"C:\dump.bin", FileMode.Create))
    {
        income.CopyTo(fs);
        fs.SetLength(Math.Max(income.Length - 8, 0));
    }
    

    Which set's the file length after it is written.