Kompresja i dekompresja plików w .zip w C# (z użyciem wbudowanych funkcji Windows)

Klasa ZipFilesHelper pozwala na pakowanie i rozpakowywanie zawartości wybranych folderów do archiwów .zip. Operacje wykonywane są w oparciu o funkcjonalności zawarte w powłoce Windows: tzw. foldery skompresowane.

Projekt musi zawierać referencję do "Microsoft Shell Controls And Automation" (zakładka COM).

using System;
using System.IO;
using System.Runtime.InteropServices;
using Shell32;

namespace ZipZipFilesHelper
{
  public static class ZipFilesHelper
  {

  
    private static void Compress(string SourceFolderPath, string DestinationZipFilePath, bool OnlyFolderItems)
    {
      File.WriteAllText(DestinationZipFilePath, "PK\x05\x06" + new String('\0', 18));
      Shell shell = new Shell32.Shell();
      Folder SrcFolder = shell.NameSpace(SourceFolderPath);
      Folder DestFolder = shell.NameSpace(DestinationZipFilePath);
      if (OnlyFolderItems)
      {
        FolderItems items = SrcFolder.Items();
        DestFolder.CopyHere(items, 0);
      }
      else
        DestFolder.CopyHere(SrcFolder, 0);
      Marshal.FinalReleaseComObject(shell);
    }
  
  
  
    // Rozpakowuje do wskazaqnego folderu
    public static void UnCompress(string SourceZipFilePath, string DestinationFolderPath)
    {
      if(!Directory.Exists(DestinationFolderPath))
        Directory.CreateDirectory(DestinationFolderPath);
      Shell shell = new Shell32.Shell();
      Folder DestFolder = shell.NameSpace(DestinationFolderPath);
      Folder Src = shell.NameSpace(SourceZipFilePath);
      FolderItems items = Src.Items();
      DestFolder.CopyHere(items, 0);
      Marshal.FinalReleaseComObject(shell);
    }

	
	
    // Rozpakowuje do tego samego folderu ("extract here")
    public static void UnCompress(string SourceZipFilePath)
    {
      string DestinationFolderPath = Path.GetDirectoryName(SourceZipFilePath);
      UnCompress(SourceZipFilePath, DestinationFolderPath);
    }

	
	
    // Pakuje elementy (pliki i podkatalogi) ze wskazanego folderu
    public static void CompressFolderItems(string SourceFolderPath, string DestinationZipFilePath)
    {
      Compress(SourceFolderPath, DestinationZipFilePath, true);
    }
	
    
    // Pakuje zawartość folderu razem z nim (głównym katalogiem w folderze skompresowanym będzie SourceFolderPath)
    public static void CompressFolder(string SourceFolderPath, string DestinationZipFilePath)
    {
      Compress(SourceFolderPath, DestinationZipFilePath, false);
    }

  }
}