How to: Resolve File Conflicts when Unzipping

  • 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.

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;
        }