4

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.

DAXaholic
  • 33,312
  • 6
  • 76
  • 74
user3900456
  • 2,003
  • 3
  • 25
  • 33
  • You might want to try to push it through a queue: read a chunk of manageable size, push it into queue, read all but 8 bytes from queue, write to output stream, repeat. – n0rd Aug 01 '16 at 04:28
  • do you have any sample code? – user3900456 Aug 01 '16 at 04:32

1 Answers1

1

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.

DAXaholic
  • 33,312
  • 6
  • 76
  • 74
  • would this be ok with huge files, like 4gb? – user3900456 Aug 01 '16 at 04:25
  • Well initially writing 8 bytes 'too much' when talking about 4 GB shouldn't be a problem and trimming a file from the end does not involve a complete rewrite of the file so from the performance point of view it should be ok. – DAXaholic Aug 01 '16 at 04:27
  • 1
    @user3900456 This is the best most efficient way to remove the last few characters from a file. [Look here](http://stackoverflow.com/a/15312386/6438653). –  Aug 01 '16 at 04:35