We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

Compress Multiple Files in a Folder to ZIP Format using C# .NET Code

Hi, I tried to compress multiple files in a Zip file using the official example below :
public class CompressMultipleFiles
{
public static void Run()
{
string dataDir = RunExamples.GetDataDir_Data();
//ExStart: CompressMultipleFiles
using (FileStream zipFile = File.Open(dataDir + “CompressMultipleFiles_out.zip”, FileMode.Create))
{
using (FileStream source1 = File.Open(dataDir + “alice29.txt”, FileMode.Open, FileAccess.Read))
{
using (FileStream source2 = File.Open(dataDir + “asyoulik.txt”, FileMode.Open, FileAccess.Read))
{
using (var archive = new Archive())
{
archive.CreateEntry(“alice29.txt”, source1);
archive.CreateEntry(“asyoulik.txt”, source2);
archive.Save(zipFile, new ArchiveSaveOptions() { Encoding = Encoding.ASCII, ArchiveComment = “There are two poems from Canterbury corpus” });
}
}
}
}
//ExEnd: CompressMultipleFiles
}
}
The issue is : How to do that if I have 50 or more files => I have to do a foreach loop but how to handle the “using inside using inside using…” operations ?
Many thanks for your help.

@Zan135,

You can compress multiple files in a folder to ZIP format by using the following C# code of Aspose.ZIP for .NET API:

string[] filePaths = Directory.GetFiles("C:\\aspose zip\\", "*.*", SearchOption.TopDirectoryOnly);

using (FileStream zipFile = File.Open("C:\\Temp\\output.zip", FileMode.Create))
{
    using (Archive archive = new Archive(new ArchiveEntrySettings(new StoreCompressionSettings())))
    {
        foreach (string filePath in filePaths)
        {
            string[] splits = filePath.Split(new char[] { '\\' });
            string fileName = splits[splits.Length - 1];

            archive.CreateEntry(fileName, filePath);
        }

        archive.Save(zipFile, new ArchiveSaveOptions() { Encoding = Encoding.ASCII });
    }
}