// C# version 3.0
using System;
using System.IO;
using System.Text;
using Shell32; // Reference to C:\WINDOWS\system32\shell32.dll
public static class Zipper {
public static void Compress(string zipFileName, params string[] fileNames) {
//Create an empty zip file
byte[] emptyzip = new byte[] {80, 75, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
using (FileStream fileStream = File.Create(zipFileName)) {
fileStream.Write(emptyzip, 0, emptyzip.Length);
fileStream.Flush();
fileStream.Close();
}
Add(zipFileName, fileNames);
}
public static void Add(string zipFileName, params string[] fileNames) {
Folder destFolder = new ShellClass().NameSpace(zipFileName);
foreach (string filename in fileNames)
destFolder.CopyHere(filename, 20);
}
public static void Extract(string zipFileName, string targetPath) {
Folder srcFolder = new ShellClass().NameSpace(zipFileName);
Folder dstFolder = new ShellClass().NameSpace(targetPath);
dstFolder.CopyHere(srcFolder.Items(), 20);
}
}
// Zipper test
internal class Program {
private static void Main(string[] args) {
FileInfo zipFileInfo = new FileInfo(Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + ".zip"));
if (zipFileInfo.Exists)
zipFileInfo.Delete();
Zipper.Compress(zipFileInfo.FullName); // just create empty zip-file
DirectoryInfo sourceDir = new DirectoryInfo(Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()));
if (!sourceDir.Exists)
sourceDir.Create();
for (int i = 0; i < 31; i++) {
FileInfo fileInfo = new FileInfo(Path.Combine(sourceDir.FullName, Path.GetRandomFileName()));
if (!fileInfo.Exists) {
using (FileStream fileStream = fileInfo.Create()) {
for (int j = 0; j < 15; j++) {
byte[] bytes = Encoding.Default.GetBytes(fileInfo.FullName + Environment.NewLine);
fileStream.Write(bytes, 0, bytes.Length);
}
fileStream.Close();
}
}
Zipper.Add(zipFileInfo.FullName, fileInfo.FullName);
}
DirectoryInfo targetDir = new DirectoryInfo(Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()));
if (!targetDir.Exists)
targetDir.Create();
Zipper.Extract(zipFileInfo.FullName, targetDir.FullName);
sourceDir.Delete(true);
targetDir.Delete(true);
zipFileInfo.Delete();
}
}