如何将文件添加到现有zip存档
如何将一些文件(几乎总是单个.csv文件)添加到现有的zip文件中?
由于您使用的是.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("========================"); } } }
对于创建,提取和打开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); } } }
最简单的方法是在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"); }
其他类型的更新同样重要:
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(); }
编辑注: DotNetZip曾经住在Codeplex。 Codeplex已被关闭。 旧档案仍然[可在Codeplex] [1]获得。 看起来代码已迁移到Github:
- https://github.com/DinoChiesa/DotNetZip 。 看起来是原作者的回购。
- https://github.com/haf/DotNetZip.Semverd 。 这看起来是当前维护的版本。 它也可以通过Nuget打包到https://www.nuget.org/packages/DotNetZip/