How to Unzip the single zipped file in c#

Binumon George 161 Reputation points
2021-11-17T14:22:09.99+00:00

In my code, Using c# I have written code for a zip single file. But not able to unzip the file. Somebody helps me to unzip single file using c#?
Below I am giving the code for the zip file

private void zip(string filePath, string ZipedFilePath)
        {

            string dirRoot = @"c:\yourfolder\";

            string[] filesToZip = Directory.GetFiles(filePath, "Remote Details.txt", SearchOption.AllDirectories);
            //final archive name (I use date / time)
            string zipFileName = string.Format("zipfile-{0:yyyy-MM-dd_hh-mm-ss-tt}.zip", DateTime.Now);

            using (MemoryStream zipMS = new MemoryStream())
            {
                using (ZipArchive zipArchive = new ZipArchive(zipMS, ZipArchiveMode.Create, true))
                {
                    foreach (string fileToZip in filesToZip)
                    {

                        if (new FileInfo(fileToZip).Extension == ".zip") continue;


                        if (fileToZip.Contains("node_modules")) continue;


                        byte[] fileToZipBytes = System.IO.File.ReadAllBytes(fileToZip);


                        ZipArchiveEntry zipFileEntry = zipArchive.CreateEntry(fileToZip.Replace(dirRoot, "").Replace('\\', '/'));


                        using (Stream zipEntryStream = zipFileEntry.Open())
                        using (BinaryWriter zipFileBinary = new BinaryWriter(zipEntryStream))
                        {
                            zipFileBinary.Write(fileToZipBytes);
                        }


                    }
                }



                using (FileStream finalZipFileStream = new FileStream(@"d:\ZipedFile\Deploy_" + zipFileName, FileMode.Create))
                {
                    zipMS.Seek(0, SeekOrigin.Begin);
                    zipMS.CopyTo(finalZipFileStream);
                }

                //lstLog.Items.Add("ZIP Archive Created.");
            }

        }
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,296 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jack J Jun 24,796 Reputation points Microsoft Vendor
    2021-11-18T02:13:40.37+00:00

    @Binumon George , Based on my test, I find that I could not use your code to zip files to an zip file.

    Therefore, I modified your code based on your requirements and I also add the related code about how to unzip a zip file to a folder.

    Here is a code example you could refer to.

     static void Main(string[] args)  
            {  
                //how to zip files to a zip file  
                string ZipedFileFolder = "D:\\Zip";  
                string SourceFolder = "D:\\Test";  
                CreateZipFile(ZipedFileFolder, SourceFolder);  
      
      
                //how to unzip a existing zip file to a folder  
                string zipPath = Directory.GetFiles(ZipedFileFolder, "*.zip", SearchOption.AllDirectories).FirstOrDefault();  
                string extractPath = @"D:\Extract";  
      
                System.IO.Compression.ZipFile.ExtractToDirectory(zipPath, extractPath);  
      
      
            }  
      
            public static void CreateZipFile(string ZipedFileFolder, string SourceFolder)  
            {  
                // Create and open a new ZIP file  
                string zipFileName = string.Format("zipfile-{0:yyyy-MM-dd_hh-mm-ss-tt}.zip", DateTime.Now);  
                string zipFilepath = Path.Combine(ZipedFileFolder,zipFileName);  
                var zip = ZipFile.Open(zipFilepath, ZipArchiveMode.Create);  
                string[] filesToZip = Directory.GetFiles(SourceFolder, "*.txt", SearchOption.AllDirectories);  
                foreach (var file in filesToZip)  
                {  
                    // Add the entry for each file  
                    zip.CreateEntryFromFile(file, Path.GetFileName(file), CompressionLevel.Optimal);  
                }  
                // Dispose of the object when we are done  
                zip.Dispose();  
            }  
    

    Tested Result:

    150248-image.png


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Karen Payne MVP 35,551 Reputation points
    2021-11-18T03:10:34.05+00:00

    Hello,

    I have a complete code sample in this GitHub repository with a spinner gif, all code is asynchronous done in C#, .NET Framework 4.8 and will work with .NET Core.

    • In create code it figures out a file or a directory being zipped.
    • Unzip is a few lines of code
    • Both zip and unzip have error handling.
    • In Form1, change the path, otherwise run the code.

    150441-figure1.png

    Backend code

    using System;  
    using System.IO;  
    using System.IO.Compression;  
    using System.Threading.Tasks;  
      
    namespace CreateZipWithExtensions.Classes  
    {  
        public static class ZipHelpers  
        {  
            /// <summary>  
            /// Create an archive/zip file from either a directory or single file  
            /// </summary>  
            /// <param name="sourceName">Folder or file to create zip file for</param>  
            /// <param name="zipFileName">Name of zip file which can include a path\file name</param>  
            /// <returns>success and exception if a runtime exception was raised</returns>  
            public static async Task<(bool success, Exception exception)> CreateEntryFromAnyAsync(string sourceName, string zipFileName)  
            {  
                  
                var result =  await Task.Run(async () =>  
                {  
                    await Task.Delay(0);  
      
                    try  
                    {  
      
                        if (File.GetAttributes(sourceName).HasFlag(FileAttributes.Directory))  
                        {  
                            ZipFile.CreateFromDirectory(sourceName, zipFileName);  
                        }  
                        else  
                        {  
                            using (var zipFile = new ZipArchive(File.Create(zipFileName), ZipArchiveMode.Create))  
                            {  
                                zipFile.CreateEntryFromFile(sourceName, Path.GetFileName(sourceName));  
                            }  
                        }  
      
                        return (true, null);  
      
                    }  
                    catch (Exception ex)  
                    {  
                        return (false, ex);  
                    }  
                });  
      
                return result;  
      
            }  
      
            /// <summary>  
            /// Extract a folder under a folder in the application path  
            /// </summary>  
            /// <param name="zipFileName">Zip file to extract from</param>  
            /// <param name="unzipPath">Where to extract to</param>  
            /// <returns>success and if an exception return it</returns>  
            /// <remarks>If the unzipPath exists delete it else an exception is thrown indicating one or more files exists. If there are a lot of files consider using a Task</remarks>  
            public static (bool success, Exception exception) Unzip(string zipFileName, string unzipPath)  
            {  
                try  
                {  
                    var folderName = Path.GetFileNameWithoutExtension(zipFileName);  
      
                    if (Directory.Exists(folderName))  
                    {  
                        Directory.Delete(folderName,true);  
                    }  
      
                    ZipFile.ExtractToDirectory(zipFileName, unzipPath);  
      
                    return (true, null);  
      
                }  
                catch (Exception ex)  
                {  
                    return (false, ex);  
                }  
            }  
        }  
    }  
      
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.