title: Out of memory using BinaryWriter in C# on adding files to a zip file
body: <p>I am trying to add files to a Zip file, preserving the directory. The code below is basically working as long as I do not have files of a few 100 Mb to zip. If I just zip a directory with 1 file of about 250 Mb (on a system with plenty of memory BTW) I get an OutOfMemory exception on the <code>write.Write()</code> line. </p>
  
  <p>I already modified the code to read in chunks as it first failed when I read/wrote the whole file. I don't know why it still fails?</p>
  
  <pre><code>    using (FileStream zipToOpen = new FileStream(cZipName, eFileMode)) 
          ZipArchiveEntry readmeEntry = archive.CreateEntry(cFileToBackup
  
  );
  
      using (BinaryWriter writer = new BinaryWriter(readmeEntry.Open()))
      {
          FileStream fsData = null;                                                                // Load file into FileStream
          fsData = new FileStream(cFileFull, FileMode.Open, FileAccess.Read);
          {
              byte[] buffer = new byte[1024];
              int bytesRead = 0;
              while ((bytesRead = fsData.Read(buffer, 0, buffer.Length)) &gt; 0)
              {
                   writer.Write(buffer,0,bytesRead); // here it fails
                   fsData.Flush(); // -&gt;CHANGED  THIS TO writer.Flush() SOLVED IT - nearly..
              }
          }
          fsData.Close();
      }
  </code></pre>
  
  <p><strong>EDIT</strong>: Arkadiusz K was right that I used the flush on the reader, not the writer. After changing that, the program zips files of 1 Gb or more where it stopped at 100 Mb first. However, I get another exception when I try to zip e.g. a 6 Gb file - it stops with: System.IO.IOException was unhandled <strong>Stream was too long</strong> Source=mscorlib
  StackTrace:
  at System.IO.MemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count)  (etc)</p>
  
  <p>Does anybody have an idea why it still fails? I'd say th code should now properly read and write 1 Kb at a time?</p>