Create Zip file using C#, extracting the Zip programatically

For creating Zip file using C#, There are so many approaches we will go with simple approaches 
first we need to select a source folder and keep the files needs to be zipped and we will create a result zip path.
Now we have to add the reference of  System.IO.Compression library and System.IO.Compression.Filesystem libraries
Once you have add the references, you have to use the "CreateFromDirectory" static method for creating the Zip 
"ExtractToDirectory" method for unzipping the same

 Another approach is little bit complicated, you can create a zip file instance and update the same using the "ZipArchive" 



code for the same given below, comment if you have any doubts.




       

 static void Main(string[] args)
        {
            string filepath = @"C:\Files";
            string resultpath = @"C:\Zip\zip.zip";
            string unZippath = @"C:\UnZip";

            //Creates the zip file
            ZipFile.CreateFromDirectory(filepath, resultpath);

            // Un Zip the zip file
            ZipFile.ExtractToDirectory(resultpath, unZippath);

            // Creating new Zip file
            using (ZipArchive newFile = ZipFile.Open(@"C:\LogFiles\Zip\zip.zip", ZipArchiveMode.Create))
            {

                newFile.CreateEntryFromFile(@"C:\LogFiles\log1.txt", "log1.txt");
            }
            //Updating the Zip file
            using (ZipArchive updateFile = ZipFile.Open(@"C:\LogFiles\Zip\zip.zip", ZipArchiveMode.Update))
            {

                updateFile.CreateEntryFromFile(@"C:\LogFiles\log1.txt", "log2.txt");
            }
        }


1 comment:

  1. oh good explanation on creating zip file using c extraction..

    ReplyDelete