I've following function which creates a Zip file, it works good when the number of files are few thousands. However, this isn't a efficient solution in a time bound operation. I was wondering if an asynchronous concurrency can be added so that it will minimise the overall time taken to complete the operation.
Code:
public static void CreateZip()
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
string dirRoot = @"C:\Dir\";
//get a list of files
string[] filesToZip = Directory.GetFiles(dirRoot, "*.*",
SearchOption.AllDirectories);
string zipFileName = @"C:\Dir.zip";
using (MemoryStream zipMS = new MemoryStream())
{
using (ZipArchive zipArchive = new ZipArchive(zipMS, ZipArchiveMode.Create,
true))
{
//loop through files to add
foreach (string fileToZip in filesToZip)
{
//read the file bytes
byte[] fileToZipBytes = System.IO.File.ReadAllBytes(fileToZip);
//create the entry - this is the zipped filename
//change slashes - now it's VALID
ZipArchiveEntry zipFileEntry = zipArchive.CreateEntry(
fileToZip.Replace(dirRoot, "").Replace('\\', '/'));
//add the file contents
using (Stream zipEntryStream = zipFileEntry.Open())
using (BinaryWriter zipFileBinary = new BinaryWriter(zipEntryStream))
{
zipFileBinary.Write(fileToZipBytes);
}
}
}
using (FileStream finalZipFileStream = new FileStream(zipFileName,
FileMode.Create))
{
zipMS.Seek(0, SeekOrigin.Begin);
zipMS.CopyTo(finalZipFileStream);
}
stopwatch.Stop();
Console.WriteLine("Total time elapsed: {0}",
stopwatch.ElapsedMilliseconds / 1000);
}
}