0

I'm using System.IO.Compression's ZipArchive to modify a file within a ZIP. I need first to read the whole content (JSON), transform the JSON then truncate the file and write the new JSON to the file. At the moment I have the following code:

using (var zip = new ZipArchive(new FileStream(zipFilePath, FileMode.Open, FileAccess.ReadWrite), ZipArchiveMode.Update))
{
  using var stream = zip.GetEntry(entryName).Open();

  using var reader = new StreamReader(stream);
  using var jsonTextReader = new JsonTextReader(reader);

  var json = JObject.Load(jsonTextReader);
  PerformModifications(json);

  stream.Seek(0, SeekOrigin.Begin);
  using var writer = new StreamWriter(stream);
  using var jsonTextWriter = new JsonTextWriter(writer);
  json.WriteTo(jsonTextWriter);
}

However, the problem is: if the resulting JSON is shorter than the original version, the remainder of the original is not truncated. Therefore I need to properly truncate the file before writing to it.

How to truncate the entry before writing to it?

D.R.
  • 20,268
  • 21
  • 102
  • 205
  • Use `` FileMode.Truncate`` – Mohamed Jun 10 '20 at 15:13
  • A ZipArchive when data is modified add modify file to end of the archive. So you may have two copies of the file in the archive. The old file is removed from the Zip Directory but is still in the Archive. So if you are seeing the old file it may be due to the directory not being updated or you are still using the old directory. There are different versions of the ZIP specification and not all the TOOLS are updated to latest specification. So I've seen lost of different issues occurring when ZIP Archives are updated. – jdweng Jun 10 '20 at 15:27
  • See https://stackoverflow.com/q/46810169/62838 – Fabian Schmied Jun 10 '20 at 16:37

1 Answers1

1

You can either delete the entry before writing it back or, which I prefer, use stream.SetLength(0) to truncate the stream before writing. (See also https://stackoverflow.com/a/46810781/62838.)

Fabian Schmied
  • 3,885
  • 3
  • 30
  • 49