Skip to content

Instantly share code, notes, and snippets.

@slofurno
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slofurno/98220f9a745425a1ff36 to your computer and use it in GitHub Desktop.
Save slofurno/98220f9a745425a1ff36 to your computer and use it in GitHub Desktop.
ziparchive
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