13 Jun

Zip and Unzip Files Programmatically in C#

There are many zip library which used to be popular. I will show you two of them.(7Zip and .NET ZipArchive)
7-Zip is a open source file archiver with a high compression ratio. Most of the source code is under the GNU LGPL license.
For more information:
http://www.7-zip.org/

You can use 7-zip library for zip and unzip to the files as follow:


            //Firstly, you should set 7z.dll path.
            SevenZipExtractor.SetLibraryPath(@"C:\7z.dll");

            //Test Code:
            string[] filePaths = new string[]
            {
                @"C:\Folder1\file1.jpg",
                @"C:\Folder1\file2.txt",
                @"C:\Folder1\file1.png",
            };
            ZipFiles(filePaths, @"C:\zippedFile2.zip");

            ZipFolder(@"C:\Folder1", @"C:\zippedFile1.zip", "password");
            Unzip(@"C:\zippedFile1.zip", @"C:\Folder2", "password");

Sample methods(using 7-Zip):


        public void ZipFiles(string[] filePaths, string outputFilePath, string password = null)
        {
            var tmp = new SevenZipCompressor();
            tmp.ScanOnlyWritable = true;
            tmp.CompressFilesEncrypted(outputFilePath, password, filePaths);
        }

        public void ZipFolder(string folderPath, string outputFilePath, string password = null)
        {
            var tmp = new SevenZipCompressor();
            tmp.ScanOnlyWritable = true;
            tmp.CompressDirectory(folderPath, outputFilePath, password);
        }

        public void Unzip(string zippedFilePath, string outputFolderPath, string password = null)
        {
            SevenZipExtractor tmp = null;
            if (!string.IsNullOrEmpty(password))
                tmp = new SevenZipExtractor(zippedFilePath, password);
            else
                tmp = new SevenZipExtractor(zippedFilePath);

            tmp.ExtractArchive(outputFolderPath);
        }

In .NET framework 4.5, System.IO.Compression namespace get some new classes that allow you to work with zip files programmatically.
Sample code:


            //Zip files
            ZipArchive zip = ZipFile.Open(filePath, ZipArchiveMode.Create);
            foreach (string file in filePaths)
            {
                zip.CreateEntryFromFile(file, Path.GetFileName(file), CompressionLevel.Optimal);
            }
            zip.Dispose();

            //Unzip
            ZipFile.CreateFromDirectory(folderPath, zippedFilePath);
            ZipFile.ExtractToDirectory(zippedFilePath, outputFolderPath);

Leave a Reply

Your email address will not be published. Required fields are marked *