Created
November 13, 2012 09:43
-
-
Save yorah/4064919 to your computer and use it in GitHub Desktop.
Zip utility using System.IO.Packaging (.Net 3.0)
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.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