Back to Devexpress

How to: Resolve File Conflicts when Unzipping

officefileapi-15248-zip-compression-and-archive-api-examples-how-to-resolve-file-conflicts-when-unzipping.md

latest3.5 KB
Original Source

How to: Resolve File Conflicts when Unzipping

  • Sep 19, 2023
  • 2 minutes to read

To implement conflict resolution for file names when decompressing an archive, do the following:

  1. Call the static ZipArchive.Read method of the DevExpress.Compression.ZipArchive class. It has two overloads, so you can specify a compressed stream or a path, to archive a file as the argument of the method. The method returns a ZipArchive instance that provides access to a collection of ZipItem elements using indexed notation.
  2. Set the ZipArchiveOptionsBehavior.AllowFileOverwrite mode to AllowFileOverwriteMode.Custom.
  3. Subscribe to the ZipArchive.AllowFileOverwrite event. This event is raised for each ZipItem that conflicts with the existing file. It allows you to decide whether to overwrite an existing file with the same name or to skip it and proceed to the next item.
  4. Call the ZipItem.Extract method for each ZipItem.

This example illustrates how to handle a file name conflict when files are extracted from archive. If a file with the same name exists, the ZipArchive.AllowFileOverwrite event occurs. You can handle this event and determine that if the file in the folder is newer than the zip item, the file in the folder should not be overwritten.

View Example

csharp
using DevExpress.Compression;

public void UnzipArchiveConflict() {
    string pathToZipArchive = "Documents\\Example.zip";
    string pathToExtract = "Documents\\!Extracted";
    using (ZipArchive archive = ZipArchive.Read(pathToZipArchive)) {
        archive.OptionsBehavior.AllowFileOverwrite = AllowFileOverwriteMode.Custom;
        archive.AllowFileOverwrite += archive_AllowFileOverwrite;
        foreach (ZipItem item in archive) {
            item.Extract(pathToExtract);
        }
    }
}

private void archive_AllowFileOverwrite(object sender, AllowFileOverwriteEventArgs e) {
    FileInfo fi = new FileInfo(e.TargetFilePath);
    if (e.ZipItem.LastWriteTime < fi.LastWriteTime) e.Cancel = true;
}
vb
Imports DevExpress.Compression

Public Sub UnzipArchiveConflict()
    Dim pathToZipArchive As String = "Documents\Example.zip"
    Dim pathToExtract As String = "Documents\!Extracted"
    Using archive As ZipArchive = ZipArchive.Read(pathToZipArchive)
        archive.OptionsBehavior.AllowFileOverwrite = AllowFileOverwriteMode.Custom
        AddHandler archive.AllowFileOverwrite, AddressOf archive_AllowFileOverwrite
        For Each item As ZipItem In archive
            item.Extract(pathToExtract)
        Next item
    End Using
End Sub

Private Sub archive_AllowFileOverwrite(ByVal sender As Object, ByVal e As AllowFileOverwriteEventArgs)
    Dim fi As New FileInfo(e.TargetFilePath)
    If e.ZipItem.LastWriteTime < fi.LastWriteTime Then
        e.Cancel = True
    End If
End Sub