Cancel ZIP archive creation
It may happen you want to cancel zip archive creation for various reasons. It just can take too long or you do not actually need some entries there.
Overview
There is an EventsBag class which are container for archive-related events. Now it supports one event - EntryCompressed. It raises after an archive entry has been compressed, and it cancelable.
Canceling long archive creation
Lets say you want your ZIP archive to be composed in about a minute. After some entry has been compressed check the time taken from the beginning of compression, and if it took more than a minute, cancel the process. The result archive would have already compressed entries including the one triggred the event.
Steps: To Canceling Long Archive Creation in C#
- Initialize a new
Archive
object to handle the compression. - Start a stopwatch to track the duration of the compression process.
- Create archive entries from a directory using the
CreateEntries
method, specifying the folder to compress. - Set up an
EventsBag
to handle compression events. - Attach an event handler for the
EntryCompressed
event, which checks if the elapsed time exceeds one minute and cancels the operation if necessary. - Start the stopwatch and proceed with saving the archive, passing the
EventsBag
in theArchiveSaveOptions
.
1 using (var archive = new Archive())
2 {
3 Stopwatch sw = new Stopwatch();
4
5 archive.CreateEntries(@"D:\BigFolder");
6 EventsBag eb = new EventsBag();
7 eb.EntryCompressed += delegate(object sender, CancelEntryEventArgs args)
8 {
9 if (sw.Elapsed > TimeSpan.FromSeconds(60))
10 args.Cancel = true;
11 };
12 sw.Start();
13 archive.Save("output.zip", new ArchiveSaveOptions() { EventsBag = eb });
14 }
Canceling after certain entry
If you want to cancel after particular entry has been compressed use following snippet:
Steps: canceling the archive creation after a specific entry is compressed in C#
- Initialize a new
Archive
object to handle the compression. - Use the
CreateEntries
method to add files from a specified directory. - Set up an
EventsBag
to manage compression events. - Attach an event handler for the
EntryCompressed
event, which checks if the entry being compressed matches a specific file name (e.g., “last.bin”). - If the target entry is found, trigger the cancellation.
- Save the archive with the
EventsBag
included in theArchiveSaveOptions
.
1 using (var archive = new Archive())
2 {
3 archive.CreateEntries(@"D:\BigFolder");
4 EventsBag eb = new EventsBag();
5 eb.EntryCompressed += delegate(object sender, CancelEntryEventArgs args)
6 {
7 if (args.Entry.Name == @"BigFolder\last.bin")
8 args.Cancel = true;
9 };
10 archive.Save("output.zip", new ArchiveSaveOptions() { EventsBag = eb });
11 }