Skip to content

Instantly share code, notes, and snippets.

@yorah
Created November 13, 2012 09:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yorah/4064919 to your computer and use it in GitHub Desktop.
Save yorah/4064919 to your computer and use it in GitHub Desktop.
Zip utility using System.IO.Packaging (.Net 3.0)
using System;
using System.Diagnostics;
using System.IO;
using System.IO.Packaging;
namespace ZipZip
{
class Program
{
static void Main(string[] args)
{
PackageFile.CreateFromDirectory(@"d:\testzip", @"d:\test.zip");
}
}
public class PackageFile
{
public static void CreateFromDirectory(string folderPath, string zipPath)
{
Debug.Assert(Path.IsPathRooted(folderPath));
Debug.Assert(Path.IsPathRooted(zipPath));
using (Package pkg = Package.Open(zipPath, FileMode.CreateNew))
{
string[] filesPaths = Directory.GetFiles(folderPath, "*", SearchOption.AllDirectories);
foreach (string filePath in filesPaths)
{
string relativePath = Path.Combine(Path.GetDirectoryName(filePath).Replace(folderPath, "."),
Path.GetFileName(filePath));
Uri uri = PackUriHelper.CreatePartUri(new Uri(relativePath, UriKind.Relative));
PackagePart packagePartDocument = pkg.CreatePart(uri, System.Net.Mime.MediaTypeNames.Text.Xml, CompressionOption.Normal);
using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
CopyStream(fileStream, packagePartDocument.GetStream());
}
}
}
}
private static void CopyStream(Stream source, Stream target)
{
const int bufSize = 0x1000;
var buf = new byte[bufSize];
int bytesRead = 0;
while ((bytesRead = source.Read(buf, 0, bufSize)) > 0)
target.Write(buf, 0, bytesRead);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment