Search code examples
c#.netzip

How to copy file from zipArchive into another zipArchive without unzipping - in c#


I want to get an entry from zipArchive1 added to zipArchive2 without unzipping zipArchive1.

using (var zipArchive1 = ZipFile.Open(zipFile1, ZipArchiveMode.Read))
{
    using (var zipArchive2 = ZipFile.Open(zipFile2, ZipArchiveMode.Update))
    {
        var entry = zipArchive1.GetEntry("fileName");
        
        // I want to do something like
        // zipArchive2.Add(entry) 
    }
}

Solution

  • Here it is:

    using (ZipArchive sourceArchive = ZipFile.OpenRead(sourceZip))
    {
        var entry = sourceArchive.GetEntry(fileFromSource);
        using (ZipArchive destArchive = ZipFile.Open(destZip, ZipArchiveMode.Update))
        {
            using (var existinFileStream = entry.Open())
            {
                var newFile = destArchive.CreateEntry(entry.FullName);
                using (var newFileStream = newFile.Open())
                {
                    existinFileStream.CopyTo(newFileStream);
                }
            }
        }
    }
    

    Where sourceZip and destZip are paths to your zip files and fileFromSource is name of the file in source archive.