0

How to write (append) data to an existing file before?

using (var memoryStream = new MemoryStream())
{
   using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
   {
       foreach (KeyValuePair<string, byte[]> file in files)
       {
          ZipArchiveEntry orderEntry = archive.CreateEntry(file.Key, CompressionLevel.Optimal); //create a file with this name
          var writer = new BinaryWriter(orderEntry.Open());
          writer.Write(file.Value); //write the binary data
       }
   }
   return memoryStream.ToArray();
}

First: Data.Add("Filename.txt", byteArray());
Two: Data.Add("Filename.txt", byteArray());

All data should be written to one file, and it creates a copy

  • Shouldn't `ZipArchiveMode.Create` be `ZipArchiveMode.Update`? – MaartenDev Oct 16 '21 at 12:22
  • Does this help? https://stackoverflow.com/a/53695616/4800344 – Ermiya Eskandary Oct 16 '21 at 12:34
  • @ErmiyaEskandary, At the output, an empty archive is obtained with this method. – Andrey Vasiliykov Oct 16 '21 at 12:38
  • Can't you modify the file all in once and then add it in one go? – Ermiya Eskandary Oct 16 '21 at 12:39
  • @ErmiyaEskandary, I use `Dictionary`, file data and file name add to dictionary. Then I use the recording of all data to the archive once. But the result is different. – Andrey Vasiliykov Oct 16 '21 at 12:45
  • You are clearly missing a using block, `using(writer = new BinaryWriter(orderEntry.Open()))`... but I can't understand what you goal is. Do you want to append alle the byte-arrays in your dictionary values into a single file in the ZipArchive? Try rewording a bit ;) – Steeeve Oct 16 '21 at 13:02
  • @Steeeve, I want to add additional text to the previous one in the file to which the text was already added earlier, after that I want to write one more text to the same file (overwrite the file) (Sorry for my English) – Andrey Vasiliykov Oct 16 '21 at 13:10
  • You can't directly append to an existing ZipArchiveEntry. Try extracting it first to a MemoryStream, append the additional content from your dictionary to that MemoryStream and recreate the entry from the MemoryStream. – Steeeve Oct 16 '21 at 13:14
  • I would be grateful for the code – Andrey Vasiliykov Oct 16 '21 at 13:16

0 Answers0