SoFunction
Updated on 2025-03-08

Implement compression and decompression of files and folders based on C#

There are several ways to compress and decompress files and folders in C#:

ZipFile (newly provided compression class in the .NET 4.5 namespace)

ZipArchive

SharpZipLib and DotNetZip

Use third-party compression software

Using ZipFile

References to .NET 4.5 assembly: and .

    public class CompressionHelper
    {
        /// <summary>
        /// Compress the specified directory into a Zip file        /// </summary>
        /// <param name="folderPath">Folder Address D:/1/ </param>        /// <param name="zipPath">zip address D:/ </param>        public static void CompressDirectoryZip(string folderPath, string zipPath)
        {
            DirectoryInfo directoryInfo = new DirectoryInfo(zipPath);
 
            if ( != null)
            {
                directoryInfo = ;
            }
 
            if (!)
            {
                ();
            }
 
            (folderPath, zipPath, , false);
        }
 
        /// &lt;summary&gt;
        /// Compress the specified file into a Zip file        /// &lt;/summary&gt;
        /// <param name="filePath">File address D:/ </param>        /// <param name="zipPath">zip address D:/ </param>        public static void CompressFileZip(string filePath, string zipPath)
        {
 
            FileInfo fileInfo = new FileInfo(filePath);
            string dirPath = ?.Replace("\\", "/") + "/";
            string tempPath = dirPath + () + "_temp/";
            if (!(tempPath))
            {
                (tempPath);
            }
            (tempPath + );
            CompressDirectoryZip(tempPath, zipPath);
            DirectoryInfo directory = new DirectoryInfo(tempPath);
            if ()
            {
                //Set the folder attribute to normal, such as: read-only folder to normal                 = ;
 
                (true);
            }
        }
 
 
        /// &lt;summary&gt;
        /// Unzip the Zip file to the specified directory        /// &lt;/summary&gt;
        /// <param name="zipPath">zip address D:/</param>        /// <param name="folderPath">Folder Address D:/1/</param>        public static void DecompressZip(string zipPath, string folderPath)
        {
            DirectoryInfo directoryInfo = new DirectoryInfo(folderPath);
 
            if (!)
            {
                ();
            }
 
            (zipPath, folderPath);
        }
 
    }

Using ZipArchive

    public class ZipArchiveHelper
    {
        public static void ZipFile(string sourceFilePath, string zipFilePath)
        {
            (sourceFilePath, zipFilePath);
 
            // Create and add compressed files            using (FileStream zipFileToOpen = new FileStream(sourceFilePath, ))
            {
                using (ZipArchive archive = new ZipArchive(zipFileToOpen, ))
                {
                    string filename = (zipFilePath);
                    ZipArchiveEntry readMeEntry = (filename);
                    using ( stream = ())
                    {
                        byte[] bytes = (zipFilePath);
                        (bytes, 0, );
                    }
                }
            }
        }
 
        /// &lt;summary&gt;
        /// Add files to compressed files        /// &lt;/summary&gt;
        /// &lt;param name="sourceFilePath"&gt;&lt;/param&gt;
        /// &lt;param name="zipFilePath"&gt;&lt;/param&gt;
        public static void AddZipFile(string sourceFilePath, string zipFilePath)
        {
            using (FileStream zipFileToOpen = new FileStream(zipFilePath, ))
            {
                using (ZipArchive archive = new ZipArchive(zipFileToOpen, ))
                {
                    string filename = (sourceFilePath);
                    ZipArchiveEntry readMeEntry = (filename);
                    using ( stream = ())
                    {
                        byte[] bytes = (sourceFilePath);
                        (bytes, 0, );
                    }
                }
            }
 
        }
 
        /// &lt;summary&gt;
        /// Decompress the compressed file        /// &lt;/summary&gt;
        /// &lt;param name="zipFilePath"&gt;&lt;/param&gt;
        /// &lt;param name="unzipFilePath"&gt;&lt;/param&gt;
        public static void UzipFile(string zipFilePath, string unzipFilePath)
        {
            using (FileStream instream = (zipFilePath))
            {
                using (ZipArchive zip = new ZipArchive(instream))
                {
 
                    foreach (ZipArchiveEntry et in )
                    {
                        using (Stream stream = ())
                        {
                            using (FileStream fsout = ((unzipFilePath, )))
                            {
                                (fsout);
                            }
                        }
                    }
                }
            }
        }
    }

Using SharpZipLib

    public class SharpZipLib
    {
        /// &lt;summary&gt;
        /// Compress folder        /// &lt;/summary&gt;
        /// <param name="dirPath">Folder Path</param>        /// <param name="password">Compression package settings password (Note: can be empty)</param>        /// <param name="zipFilePath">Compressed package path + name + suffix (Note: can be empty, default to the same directory)</param>        /// &lt;returns&gt;&lt;/returns&gt;
        public string ZipFiles(string dirPath, string password, string zipFilePath)
        {
            if (zipFilePath == )
            {
                // Use folder name +.zip when compressed file name is empty                zipFilePath = GetZipFilePath(dirPath);
            }
            try
            {
                string[] filenames = (dirPath);
                using (ZipOutputStream s = new ZipOutputStream((zipFilePath)))
                {
                    (9);
                     = password;
                    byte[] buffer = new byte[4096];
                    foreach (string file in filenames)
                    {
                        ZipEntry entry = new ZipEntry((file));
                         = ;
                        (entry);
                        using (FileStream fs = (file))
                        {
                            int sourceBytes;
                            do
                            {
                                sourceBytes = (buffer, 0, );
                                (buffer, 0, sourceBytes);
                            } while (sourceBytes &gt; 0);
                        }
                    }
                    ();
                    ();
                }
                return zipFilePath;
            }
            catch (Exception ex)
            {
                return ();
            }
        }
 
        /// &lt;summary&gt;
        /// Decompression folder        /// &lt;/summary&gt;
        /// <param name="zipFilePath">Compressed package address + name + suffix</param>        /// <param name="password">Password (Note: Can be empty)</param>        /// <param name="unZippath">Path saved after decompression (Note: can be empty, default to the same directory)</param>        /// &lt;returns&gt;&lt;/returns&gt;
        public string UnZips(string zipFilePath, string password, string unZippath)
        {
            try
            {
                if (unZippath == )
                {
                    // When the decompressed folder is empty, the default is the same as the compressed file in the same level directory as the compressed file, and the folder with the same name as the compressed file is                    unZippath = GetUnZipFilePath(zipFilePath);
                }
                if (CreatePath(unZippath) &amp;&amp; IsExistFilePath(zipFilePath))
                {
                    string directoryName = (unZippath);
                    {
                        using (ZipInputStream zipInStream = new ZipInputStream((zipFilePath)))
                        {
                             = password;
                            ZipEntry entry = ();
                            do
                            {
                                using (FileStream fileStreamOut = (directoryName + "\\" + ))
                                {
                                    int size = 2048;
                                    byte[] buffer = new byte[size];
                                    do
                                    {
                                        size = (buffer, 0, );
                                        (buffer, 0, size);
                                    } while (size &gt; 0);
                                    ();
                                    ();
                                }
                            } while ((entry = ()) != null);
                            ();
                            ();
                            return unZippath;
                        }
                    }
                }
                return "Please confirm whether the compressed package file address and the saved address after decompression can be accessed!";
            }
            catch (Exception ex)
            {
                return ();
            }
        }
 
        /// &lt;summary&gt;  
        /// Compress files        /// &lt;/summary&gt;  
        /// <param name="dirFilePath">File path + name + suffix</param>        /// <param name="password">Compression package settings password (Note: can be empty)</param>        /// <param name="zipFilePath">Compressed package path + name + suffix (Note: can be empty, default to the same directory)</param>        public string ZipFile(string dirFilePath, string password, string zipFilePath)
        {
            try
            {
                if (IsExistFilePath(dirFilePath))
                {
                    if (zipFilePath == )
                    {
                        zipFilePath = GetZipFilePath(((dirFilePath), ""));
                    }
                    string filename = (dirFilePath);
                    FileStream streamToZip = new FileStream(dirFilePath, , );
                    FileStream zipFile = (zipFilePath);
                    using (ZipOutputStream zipStream = new ZipOutputStream(zipFile))
                    {
                        ZipEntry zipEntry = new ZipEntry(filename);
                        (zipEntry);
                        (9);
                         = password;
                        byte[] buffer = new byte[2048];
                        System.Int32 size = (buffer, 0, );
                        (buffer, 0, size);
                        while (size &lt; )
                        {
                            int sizeRead = (buffer, 0, );
                            (buffer, 0, sizeRead);
                            size += sizeRead;
                        }
                        ();
                        ();
                        ();
                    }
                    return zipFilePath;
                }
                return "Please confirm whether the compressed package file address and the saved address after decompression can be accessed!";
            }
            catch (Exception ex)
            {
                return ();
            }
        }
 
        /// &lt;summary&gt;
        /// Create a path        /// &lt;/summary&gt;
        /// <param name="path">path</param>        /// &lt;returns&gt;&lt;/returns&gt;
        public bool CreatePath(string path)
        {
            try
            {
                if (!(path))
                {
                    (path);
                    return true;
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
 
        /// &lt;summary&gt;
        /// Whether the file exists        /// &lt;/summary&gt;
        /// <param name="filePath">Road + name + suffix</param>        /// &lt;returns&gt;&lt;/returns&gt;
        public bool IsExistFilePath(string filePath)
        {
            if (!(filePath))
            {
                return false;
            }
            return true;
        }
 
        /// &lt;summary&gt;
        /// Get the default compression path + file name + suffix [.zip]        /// &lt;/summary&gt;
        /// <param name="path">Folder path that needs to be compressed (Note: does not include. suffix)</param>        /// <returns>Same directory path as compressed file</returns>        public string GetZipFilePath(string path)
        {
            if (("\\"))
            {
                path = (0,  - 1);
            }
            return path + ".zip";
        }
 
        /// &lt;summary&gt;
        /// Get the default decompression path        /// &lt;/summary&gt;
        /// <param name="path">The file address of the compressed package that needs to be decompressed</param>        /// <returns>Same directory path as the decompressed file</returns>        public string GetUnZipFilePath(string path)
        {
            path = ((path), (path));
            if (!("/"))
            {
                path += "/";
            }
            return path;
        }
 
        /// &lt;summary&gt;
        /// Get all files in the path        /// &lt;/summary&gt;
        /// <param name="path">path</param>        /// &lt;returns&gt;&lt;/returns&gt;
        private Hashtable getAllFies(string path)
        {
            Hashtable FilesList = new Hashtable();
            DirectoryInfo fileDire = new DirectoryInfo(path);
            if ()
            {
                (fileDire, FilesList);
                ((), FilesList);
            }
            (fileDire, FilesList);
            ((), FilesList);
            return FilesList;
        }
 
        /// &lt;summary&gt;  
        /// Get all files in a folder under a folder        /// &lt;/summary&gt;  
        /// &lt;param name="dirs"&gt;&lt;/param&gt;  
        /// &lt;param name="filesList"&gt;&lt;/param&gt;  
        private void getAllDirsFiles(DirectoryInfo[] dirs, Hashtable filesList)
        {
            foreach (DirectoryInfo dir in dirs)
            {
                foreach (FileInfo file in ("*.*"))
                {
                    (, );
                }
                ((), filesList);
            }
        }
 
        /// &lt;summary&gt;  
        /// Get the file in a folder        /// &lt;/summary&gt;  
        /// <param name="strDirName">Directory name</param>        /// <param name="filesList">File List HastTable</param>        private void getAllDirFiles(DirectoryInfo dir, Hashtable filesList)
        {
            foreach (FileInfo file in ("*.*"))
            {
                (, );
            }
        }
    }

Use third-party compression software

    public  class WinrarZip
    {
        public static bool Zip(string strzipPath, string strtxtPath, string password)
        {
            try
            {
                 Process1 = new ();
                 = "";
                 = true;
                 = " a -p" + password + " " + strzipPath + " " + strtxtPath;
                //strtxtPath = "c://freezip//";
                // = " x -p123456 " + strzipPath + " " + strtxtPath;
                ();
                if ()
                {
                    return true;
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
 
        }
 
        public static bool UZip(string strzipPath, string strtxtPath, string password)
        {
            try
            {
                 Process1 = new ();
                 = "";
                 = true;
                // = " a -p123456 " + strzipPath + " " + strtxtPath;
                //strtxtPath = "c://freezip//";
                 = " x -p" + password + " " + strzipPath + " " + strtxtPath;
                ();
                if ()
                {
                    return true;
                }
                return true;
            }
            catch (Exception)
            {
 
                return false;
            }
 
        }
    }

This is the article about compressing and decompressing files and folders based on C#. For more related contents of C# compression and decompressing files, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!