Reputation: 553
How can I add some file (almost always a single .csv file) to an existing zip file?
Upvotes: 33
Views: 66898
Reputation: 4544
For creating, extracting, and opening zip archives, we can use ZipFile Class with reference: System.IO.Compression.FileSystem. For .NET 4.5.2 and below, we also need to add reference: System.IO.Compression. Here's the method for adding files to 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);
}
}
}
Upvotes: 37
Reputation: 74307
The easiest way is to get DotNetZip at http://dotnetzip.codeplex.com/
Adding files can be as easy as
String[] filenames = { @"ReadMe.txt",
@"c:\data\collection.csv" ,
@"c:\reports\AnnualSummary.pdf"
} ;
using ( ZipFile zip = new ZipFile() )
{
zip.AddFiles(filenames);
zip.Save("Archive.zip");
}
Other sorts of updates are just as trivial:
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();
}
Edited To Note: DotNetZip used to live at Codeplex. Codeplex has been shut down. The old archive is still [available at Codeplex][1]. It looks like the code has migrated to Github:
Upvotes: 7
Reputation: 61369
Since you are in .NET 4.5, you can use the ZipArchive (System.IO.Compression) class to achieve this. Here is the MSDN documentation: (MSDN).
Here is their example, it just writes text, but you could read in a .csv file and write it out to your new file. To just copy the file in, you would use CreateFileFromEntry
, which is an extension method for 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("========================");
}
}
}
Upvotes: 36