@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:
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.