Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to implement zip compression in .Net ?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 184
    Comment on it

    Hi Friends,

    Sometimes we need to compress some files programmatically in our code particularly in the case when you are developing any multiple download scenario. We compress the files for following reasons:

    1-Compressed files are smaller in size, so take lesser time to download or upload.

    2-You can use a password on a compressed file to secure the content.

    3-Even if files are not compressed, downloading all of the files at a single place is always convenient. Downloading 10 different files and all of them differently looks odd.

    So there are lots of third party tools available like jSharpLib  but .Net version 4.5 ships with in built features for compressing files. Sounds good , right? Let's get to it.

    Using .Net Compression in very simple. All you have to do is to reference the "System.IO.Compression.FileSystem" in the project and use the namespace " System.IO.Compression" where you are writing your code. So there may be two scenarios of compression:

    1-Single File Compression

    2-Multiple File Compression

    1-Single File Compression 

    We can compress a single file as following:

    using System.IO.Compression;
    
    namespace CompressionandExtraction
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Provide the folder which you want to zip
                string folderToZip = @"c:\Temp\ZipExample";
    
                //provide the path and name of the file you want to create after zipping
                string zipFile = @"c:\Temp\ZipExampleOutput\MyZippedDocuments.zip";
    
                //call the CreateFromDirectory Method
                ZipFile.CreateFromDirectory(folderToZip, zipFile);
            }
        }
    }
    

    The above code needs no explanation I think as it's a very simple code. First two strings tell the path of the folder to be zipped and the output folder name and path. After those lines there comes the core method

    public static void CreateFromDirectory( string sourceDirectoryName, string destinationArchiveFileName, CompressionLevel compressionLevel, bool includeBaseDirectory )
    

    which does the core task of compressing a folder to zip. This method has some optional parameters which are as following:

    CompressionLevel.Fastest

    Implements the compression at fastest level even if the file is not optimally compressed.

    CompressionLevel.NoCompression

    Files are not compressed at all.

    CompressionLevel.Optimal

    Files are optimally compressed even if it takes longer.

    When we use these option we require one more parameter to be passed which is " includeBaseDirectory ". It tells that whether to include the name of the directory from "sourceDirectoryName" at the root of archive or just the contents. You can set it true or false depending on your choice.

    2-Compressing Multiple Files

    For compressing multiple files we can use the source and output strings same as previous code block. We can just replace the "CreateFromDirectory" method with following one:

    /*Create object of ZipArchiveClass by calling Open method of ZipFile Class and Archive mode to create */
    using (ZipArchive zipArchive = ZipFile.Open(zipFile, ZipArchiveMode.Create))
    {
        /*Get the reference of the files to be archived inside "folderToZip"*/
        DirectoryInfo di = new DirectoryInfo(folderToZip);
        FileInfo[] filesToCompress = di.GetFiles();
     
        
        if (filesToCompress != null && filesToCompress .Length > 0)
        {
            //iterate filesToCompress array for each file
            foreach (FileInfo fileToCompress in filesToCompress )
            {
                zipArchive.CreateEntryFromFile(fileToCompress .FullName, fileToCompress .Name, CompressionLevel.Optimal);
            }
        } 
    }

    Now you'll find that you're getting an error for the "ZipArchive Class". Just provide a reference to  the " System.IO.Compression " class and it'll be gone.

    Following is the step by step application of the above code:

    1-Keep the "folderToZip" and "zipFile" varaible intact.

     string folderToZip = @"c:\Temp\ZipExample";
    
     string zipFile = @"c:\Temp\ZipExampleOutput\MyZippedDocuments.zip";
    

    2- Take a using block(I think you know the purpose) and instantiate ZipArchive Class  with ZipFile.OpenMethod( It opens a zip archive at the specified path and in the specified mode ).

    using (ZipArchive zipArchive = ZipFile.Open(zipFile, ZipArchiveMode.Create))
    {
    /*Code for compression*/
    }

    3-Take all the files in the folder to zip in a FileInfoArray so that we can loop through the files in the next step.

     DirectoryInfo di = new DirectoryInfo(folderToZip);
     FileInfo[] filesToCompress = di.GetFiles();
     

    4-Loop through the files and call the " CreateEntryFromFile" method which takes source and destination path and CompressionLevel as parameters

    if (filesToCompress != null && filesToCompress .Length > 0)
        {
            //iterate filesToCompress array for each file
            foreach (FileInfo fileToCompress in filesToCompress )
            {
                zipArchive.CreateEntryFromFile(fileToCompress .FullName, fileToCompress .Name, CompressionLevel.Optimal);
            }
        } 

    So we've seen the compression of single and multiple files. You can extend it to any level and make your app like WinRAR etc. Third party tools are good but finding something in our very own .Net Framework is always satisfying and pleasing.

    Thank You.

    Happy Coding:-)

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: