Last active
August 29, 2015 14:19
-
-
Save slofurno/98220f9a745425a1ff36 to your computer and use it in GitHub Desktop.
ziparchive
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.IO.Compression; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace ConsoleApplication5 | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var ms = new MemoryStream(); | |
var directory = new DirectoryInfo("files"); | |
FileInfo[] files = directory.GetFiles(); | |
var filestreams = new List<NamedStream>(); | |
foreach (var file in files) | |
{ | |
using (var fs = file.OpenRead()) | |
{ | |
var ns = new NamedStream(); | |
fs.CopyTo(ns); | |
ns.Name = file.Name; | |
filestreams.Add(ns); | |
} | |
} | |
using (var fs = File.OpenWrite("output.zip")) | |
using (var zipped = ZipSomeFiles(filestreams)) | |
{ | |
zipped.CopyTo(fs); | |
} | |
} | |
static MemoryStream ZipSomeFiles(IEnumerable<NamedStream> files) | |
{ | |
var ms = new MemoryStream(); | |
using (var zip = new ZipArchive(ms, ZipArchiveMode.Update, true)) | |
{ | |
foreach (NamedStream file in files) | |
{ | |
var zipentry = zip.CreateEntry(file.Name, CompressionLevel.Optimal); | |
using (var entry = zipentry.Open()) | |
{ | |
file.Position = 0; | |
file.CopyTo(entry); | |
file.Flush();//not needed in this example | |
} | |
} | |
} | |
ms.Position = 0; | |
return ms; | |
} | |
} | |
public class NamedStream : MemoryStream | |
{ | |
public string Name { get; set; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment