如何将文件添加到现有zip存档

use*_*397 15 c# zipfile

如何将一些文件(几乎总是单个.csv文件)添加到现有的zip文件中?

Bra*_*NET 25

由于您使用的是.NET 4.5,因此可以使用ZipArchive(System.IO.Compression)类来实现此目的.这是MSDN文档:(MSDN).

这是他们的示例,它只是写文本,但您可以读取.csv文件并将其写入新文件.要只是复制文件,你会使用CreateFileFromEntry,这是一个扩展方法ZipArchive.

using (FileStream zipToOpen = new FileStream(@"c:\users\exampleuser\release.zip", FileMode.Open))
{
   using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
   {
       ZipArchiveEntry readmeEntry = archive.CreateEntry("Readme.txt");
       using (StreamWriter writer = new StreamWriter(readmeEntry.Open()))
       {
           writer.WriteLine("Information about this package.");
           writer.WriteLine("========================");
       }
   }
}
Run Code Online (Sandbox Code Playgroud)


Fei*_*hou 15

对于创建,提取和打开zip存档,我们可以使用ZipFile类,参考:System.IO.Compression.FileSystem.对于.NET 4.5.2及更低版本,我们还需要添加引用:System.IO.Compression.这是将文件添加到zip的方法:

    public static void AddFilesToZip(string zipPath, string[] files)
    {
        if (files == null || files.Length == 0)
        {
            return;
        }

        using (var zipArchive = ZipFile.Open(zipPath, ZipArchiveMode.Update))
        {
            foreach (var file in files)
            {
                var fileInfo = new FileInfo(file);
                zipArchive.CreateEntryFromFile(fileInfo.FullName,  fileInfo.Name);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)


Nic*_*rey 7

最简单的方法是在http://dotnetzip.codeplex.com/上获取DotNetZip

添加文件可以很简单

String[] filenames = { @"ReadMe.txt",
                       @"c:\data\collection.csv" ,
                       @"c:\reports\AnnualSummary.pdf"
                     } ;
using ( ZipFile zip = new ZipFile() )
{
  zip.AddFiles(filenames);
  zip.Save("Archive.zip");
}
Run Code Online (Sandbox Code Playgroud)

其他类型的更新同样重要:

using (ZipFile zip = ZipFile.Read("ExistingArchive.zip"))
{

  // update an existing item in the zip file
  zip.UpdateItem("Portfolio.doc"); 

  // remove an item from the zip file
  zip["OldData.txt"].RemoveEntry();

  // rename an item in the zip file
  zip["Internationalization.doc"].FileName = "i18n.doc";

  // add a comment to the archive
  zip.Comment = "This zip archive was updated " + System.DateTime.ToString("G");

  zip.Save();
}
Run Code Online (Sandbox Code Playgroud)

编辑注: DotNetZip曾经住在Codeplex.Codeplex已关闭.旧档案仍然[可在Codeplex] [1]获得.看起来代码已迁移到Github: