void AddFilesToZip (ITaskItem [] files, ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream) { if (files == null) return; foreach (ITaskItem item in files) { string target_path = item.GetMetadata ("TargetPath"); if (String.IsNullOrEmpty (target_path)) target_path = Path.GetFileName (item.ItemSpec); zipStream.PutNextEntry (new ICSharpCode.SharpZipLib.Zip.ZipEntry (target_path)); using (FileStream inStream = File.OpenRead (item.ItemSpec)) { int readCount; byte[] buffer = new byte[4096]; do { readCount = inStream.Read (buffer, 0, buffer.Length); zipStream.Write (buffer, 0, readCount); } while (readCount > 0); } } }
/// <summary> /// Recursive Zipping of a directory. /// </summary> /// <param name="zipStream"></param> /// <param name="baseDir"></param> /// <param name="dir"></param> /// <param name="filesToIgnore"></param> private static void ZipDirectory(ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream, DirectoryInfo baseDir, DirectoryInfo dir, string[] filesToIgnore) { var nameTransform = new ICSharpCode.SharpZipLib.Zip.ZipNameTransform(baseDir.FullName); foreach (var file in dir.GetFiles()) { if (IgnoreFile(baseDir.FullName, file.FullName, filesToIgnore)) continue; var relativeName = nameTransform.TransformFile(file.FullName); var zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(relativeName); zipStream.PutNextEntry(zipEntry); using (var fileStream = file.OpenRead()) fileStream.CopyTo(zipStream); } foreach (var subDir in dir.GetDirectories()) { if (IgnoreFile(baseDir.FullName, subDir.FullName, filesToIgnore)) continue; ZipDirectory(zipStream, baseDir, subDir, filesToIgnore); } }