0

I have the following code which works most of the time when saving a file from a memory stream pointing to a byte array to a network location.

using (var writer = new BinaryWriter(new FileStream(filePath, FileMode.Create)))
using (var reader = new BinaryReader(stream))
{
    var chunkSize = 1024;

    var chunkCount = (int)reader.BaseStream.Length / chunkSize;

    var chunks = Enumerable.Range(0, chunkCount)
                            .Select(_ => reader.ReadBytes(chunkSize));

    chunks.ForEach(c => writer.Write(c));

    writer.Write(reader.ReadBytes((int)reader.BaseStream.Length % chunkSize));

    writer.Close();
    reader.Close();
}

Is there any possible way the above code may end up saving zero bytes file? Is it a bad idea to save to the network directly and not use a "copy from temp" method?

fahadash
  • 3,133
  • 1
  • 30
  • 59
  • at which `Position` is the reader? (see: https://stackoverflow.com/questions/21969045/how-do-i-know-current-offset-of-binaryreader-in-c) – Luuk Feb 25 '20 at 13:35
  • Why not just: `using var output = new FileStream(filePath, FileMode.Create); stream.CopyTo(output);` ? – Matthew Watson Feb 25 '20 at 13:39
  • @Luuk Good question. It is zero. – fahadash Feb 25 '20 at 13:56
  • You're using integer division to calculate your chunk count. Is `chunkCount` 0? –  Feb 25 '20 at 14:21
  • 1
    Yeah, looks like that will always skip the last `reader.BaseStream.Length % chunkSize` bytes. Better to just use `CopyTo` as Matthew says. – Damien_The_Unbeliever Feb 25 '20 at 15:33
  • @Damien_The_Unbeliever Very good point. But the final modulo counter will catch that and allow the remaining bytes to be written to the device No? – fahadash Feb 25 '20 at 16:35

0 Answers0