V
V
Vlad2018-05-10 16:33:01
C++ / C#
Vlad, 2018-05-10 16:33:01

How to change a file inside a zip archive?

I have many archives, each with three files. Two of them need to be changed.

// Открываю архив
using (ZipArchive archive = new ZipArchive(ms, ZipArchiveMode.Update))
{
  // idxs - memoryStream указывающие на файлы которые надо изменить
  foreach (var idx in idxs)
  {	//десериализация xml
    var msIndex = Deserialize.SerializeObjAlt(idx.Value);
    // удаляем старый файл
    ZipArchiveEntry Entry0 = archive.GetEntry(idx.Key);
    Entry0.Delete();
    // создаем новый файл
    ZipArchiveEntry Entry1 = archive.CreateEntry(idx.Key);
    using (var writer = Entry1.Open())
    {
      msIndex.Position = 0;
      msIndex.CopyTo(writer);
    }
  }
}

But unfortunately it does not work - the archive is unchanged. What could have gone wrong??

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vlad, 2018-05-11
@KislyFan

Just add Flush

using (var writer = Entry1.Open())
    {
      msIndex.Position = 0;
      msIndex.CopyTo(writer);
      writer.Flush();
    }

O
Ogoun Er, 2018-06-19
@Ogoun

1. Create a temporary directory
2. Unpack files into it
3. Modify files
4. Pack the directory into an archive
5. Delete the temporary directory
In the System.IO.Compression.FileSystem.dll namespace, there is a convenient ZipFile class that can both pack and unpack directories.
ZipFile.CreateFromDirectory(tmp, zipPath);
ZipFile.ExtractToDirectory(zipFile, targetFolder);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question