Create Zip archive from multiple in memory files in C#

后端 未结 8 1899
情话喂你
情话喂你 2020-12-13 02:06

Is there a way to create a Zip archive that contains multiple files, when the files are currently in memory? The files I want to save are really just text only and are stor

8条回答
  •  抹茶落季
    2020-12-13 02:48

    Use ZipEntry and PutNextEntry() for this. The following shows how to do it for a file, but for an in-memory object just use a MemoryStream

    FileStream fZip = File.Create(compressedOutputFile);
    ZipOutputStream zipOStream = new ZipOutputStream(fZip);
    foreach (FileInfo fi in allfiles)
    {
        ZipEntry entry = new ZipEntry((fi.Name));
        zipOStream.PutNextEntry(entry);
        FileStream fs = File.OpenRead(fi.FullName);
        try
        {
            byte[] transferBuffer[1024];
            do
            {
                bytesRead = fs.Read(transferBuffer, 0, transferBuffer.Length);
                zipOStream.Write(transferBuffer, 0, bytesRead);
            }
            while (bytesRead > 0);
        }
        finally
        {
            fs.Close();
        }
    }
    zipOStream.Finish();
    zipOStream.Close();
    

提交回复
热议问题