Skip to main content

How to: Filter Files to Archive

  • 2 minutes to read

To only archive files that meet a certain criteria, do the following:

  1. Create a ZipArchive class instance.
  2. Subscribe to its ZipArchive.ItemAdding event. This event is raised for each ZipItem that holds information for a file or directory. Add event handler code to analyze the ZipItem and specify the action to perform – to continue archiving, to stop the process or to cancel adding this particular item to an archive.
  3. Call the ZipArchive.AddFile method for each selected file.
  4. Call the ZipArchive.Save method to create an archive and save it to a specified location.

This example demonstrates how to handle the ZipArchive.ItemAdding event to decide for each file whether it should be included in the archive.

If a file creation date is not the current date, the file is not added to the archive. A volatile variable is used to indicate whether the process should be stopped - it can be useful to interrupt archive creation if too many files are specified.

View Example

using DevExpress.Compression;
//...
volatile bool stopArchiving = false;

public void FilterArchiveFiles() {
    string[] sourceFiles = this.sourceFiles;
    using (ZipArchive archive = new ZipArchive()) {
        archive.ItemAdding += archive_ItemAdding;
        foreach (string file in sourceFiles) {
            archive.AddFile(file, "/");
        }
        archive.Save("FilterArchiveFiles.zip");
    }
}

private void archive_ItemAdding(object sender, ZipItemAddingEventArgs args) {
    if (args.Item.CreationTime.Date != DateTime.Today)
        args.Action = ZipItemAddingAction.Cancel;
    if (stopArchiving) args.Action = ZipItemAddingAction.Stop;
}