Search code examples
c#.netzip

ZipArchive, update entry: read - truncate - write


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?


Solution

  • 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.)