Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcefully Replacing Existing Files during Extracting File using System.IO.Compression?

Tags:

c#

I am using the following code to extract all files in a folder

        using (ZipArchive archive = new ZipArchive(zipStream))         {             archive.ExtractToDirectory(location);         } 

But if one file exist then it throws an exception. Is there is any way to tell the Compression API to replace the existing files.

I found one way is to get all the file names first then check whether file exist and delete it. But this is somehow very costly for me.

like image 560
Imran Qadir Baksh - Baloch Avatar asked Feb 10 '13 06:02

Imran Qadir Baksh - Baloch


People also ask

What does extract and replace files mean?

What It Means. Extract all files. Extracts all selected files, including older versions of files that are already in the destination folder. If the Overwrite setting is Prompt user, Smartcrypt asks before overwriting newer files already in the folder. Freshen existing files only.


1 Answers

I have created an extension. any comment to it improve will be appreciated,

public static class ZipArchiveExtensions {     public static void ExtractToDirectory(this ZipArchive archive, string destinationDirectoryName, bool overwrite)     {         if (!overwrite)         {             archive.ExtractToDirectory(destinationDirectoryName);             return;         }          DirectoryInfo di = Directory.CreateDirectory(destinationDirectoryName);         string destinationDirectoryFullPath = di.FullName;          foreach (ZipArchiveEntry file in archive.Entries)         {             string completeFileName = Path.GetFullPath(Path.Combine(destinationDirectoryFullPath, file.FullName));              if (!completeFileName.StartsWith(destinationDirectoryFullPath, StringComparison.OrdinalIgnoreCase))             {                 throw new IOException("Trying to extract file outside of destination directory. See this link for more info: https://snyk.io/research/zip-slip-vulnerability");             }              if (file.Name == "")             {// Assuming Empty for Directory                 Directory.CreateDirectory(Path.GetDirectoryName(completeFileName));                 continue;             }             file.ExtractToFile(completeFileName, true);         }     } } 
like image 196
Imran Qadir Baksh - Baloch Avatar answered Sep 28 '22 18:09

Imran Qadir Baksh - Baloch