Back to Devexpress

How to: Filter Files to Archive

officefileapi-15241-zip-compression-and-archive-api-examples-how-to-filter-files-to-archive.md

latest3.0 KB
Original Source

How to: Filter Files to Archive

  • Sep 19, 2023
  • 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

csharp
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;
}
vb
Imports DevExpress.Compression

volatile bool stopArchiving = False

Private stopArchiving As Boolean = False
Public Sub FilterArchiveFiles()
    Dim sourceFiles() As String = Me.sourceFiles
    Using archive As New ZipArchive()
        AddHandler archive.ItemAdding, AddressOf archive_ItemAdding
        For Each file As String In Me.sourceFiles
            archive.AddFile(file, "/")
        Next file
        archive.Save("Documents\FilterArchiveFiles.zip")
    End Using
End Sub

Private Sub archive_ItemAdding(ByVal sender As Object, ByVal args As ZipItemAddingEventArgs)
    If args.Item.CreationTime.Date <> DateTime.Today Then
        args.Action = ZipItemAddingAction.Cancel
    End If
    If stopArchiving Then
        args.Action = ZipItemAddingAction.Stop
    End If
End Sub