Compression and Decompression in .Net

01 Nov 2013, 12:03 PM

Introduction

Compression and decompression is one of the exciting features of .Net framework 4.5. In previous versions developer were always worry to find some third party APIs for compression. But finally Microsoft has resolved their problem and provided the API for this purpose.

The new namespace System.IO.Compression contains the different type of compressing and decompressing files and streams.

  • ZipFile
  • ZipArchive
  • ZipArchiveEntry
  • DeflateStream
  • GZipStream

You can use following classes to compress or decompress you file or stream. For using them add two namespaces in your project

  • System.IO.Compression
  • System.IO.Compression.FileSystem

In this blog we will explain some of the functions that you can use for compress and decompress using ZipFile class. ZipFile class exposes static methods to compress or decompress the content of folder.

Compression Using ZipFile

To compress the folder content pass the folder name and the zip file name to the CreateFromDirectory method. See the example below.

 public static void ZipDirectory()
 {
       
    var sourceDirectory = @"c:\MyData";
    var zipPath = @"c:\MyData.zip";

    ZipFile.CreateFromDirectory(sourceDirectory, zipPath);

 }  

CreateFromDirectory method has three overloaded methods. You can also pass CompressionLevel and Encoding to the other variation of this method.

Decompression Using ZipFile

ZipFile also provides a static method for extracting archive file.

        
 public static void ExtractDirectory()
 {
        
        var path = @"c:\MyData_new";
        var zipPath = @"c:\MyData.zip";

        ZipFile.ExtractToDirectory(zipPath, path);

 }
    
    

ExtractToDirectory method simple extract add the file in the destination folder. You can also pass Encoding while extracting.

Decompress/Extract Specific Contents Only

You can also iterate through the contents of the .zip file and extract the specific files from zip file. Use ZipFile.OpenRead() to open zip archive and iterate through content by content and extract the required files. In next example we are extracting .txt files from the .zip file.

        
 public static void ExtractTextFilesOnly()
 {
        var path = @"c:\MyData_new";
        var zipFile = @"c:\MyData.zip";
        
        if(!Directory.Exists(path))
            Directory.CreateDirectory(path);

        
        using (ZipArchive archive = ZipFile.OpenRead(zipFile))
        {
            foreach (ZipArchiveEntry entry in archive.Entries)
            {
                if (entry.FullName.EndsWith(".txt", StringComparison.OrdinalIgnoreCase))
                {
                    entry.ExtractToFile(Path.Combine(path, entry.FullName));
                }
             }
        }
  }

    

The ZipFile.Open() method returns the object of ZipArchive that contains the all contents or files in ZipArchiveEntry object. Traverse each entry one by one and extract required file using entry.ExtractToFile() method.

Add file/content in existing Zip

You can also add contents into the existing zip archive file using ZipArchive class.In the next example we will add text file in the existing zip archive file.

        
 public static void AddFileInExistingZip()
 {
    var zipFile = @"c:\MyData.zip";
    var newFile = @"c:\newFile.txt";

    using (FileStream zipArchive = new FileStream(zipFile, FileMode.Open))
    {
        using (ZipArchive archive = new ZipArchive(zipArchive, ZipArchiveMode.Update))
        {
            ZipArchiveEntry newEntry = archive.CreateEntryFromFile(newFile, "newFile.txt");
        }
    }
 }
    

Open the file stream and pass it to the ZipArchive object and use archive.CreateEntryFromFile() method to add new file in the existing archive.

You can also write stream into the existing zip archive. In the next example you will see how we can do that.

 public static void AddFileOnFilyInExistingZip()
 {
    
    var zipFile = @"c:\MyData.zip";
    
    using (FileStream zipArchive = new FileStream(zipFile, FileMode.Open))
    {
    
        using (ZipArchive archive = new ZipArchive(zipArchive, ZipArchiveMode.Update))
        {
    
            ZipArchiveEntry infoEntry = archive.CreateEntry("Info.txt");
            using (StreamWriter sw = new StreamWriter(infoEntry.Open()))
            {
                sw.WriteLine("Information about the newly archive.");
                sw.WriteLine("-------------------------------------");
                sw.WriteLine("Line - 1");
                sw.WriteLine("Line - 2");
            }
        }
    }
 }

It is also pretty simple just create new entry in archive file using archive.CreateEntry("Info.txt") statement write content in the file using StreamWriter.

About Blog
How to Zip and Unzip file in C#

Date 01 Nov 2013, 11:27 AM
Views 8,510
;