Unzip files using Shell32 in C#
The .NET Framework didn’t have an easy way for developers to unzip files resulting to a lot of people having to use third party libraries to achieve that functionality. This was until the .NET Framework 4.5 was released which had a new class called ZipFile that simplified the process of unzipping files..
But since targeting the .NET Framework 4.5 might not be ideal in many cases, mainly because its adaptation rate is still fairly low I will demostrate another way to unzip .zip files with the use of Shell32.
Firstly you will need to reference in your project the COM library called Microsoft Shell Controls And Automation (Interop.Shell32.dll) in order to be able to access the Shell32 namespace.
The method below is a simple example that takes two parameters. The .zip file location and the folder destination where the files will be extracted to.
public static void UnZip(string zipFile, string folderPath)
throw new FileNotFoundException();
Shell32.Shell objShell = new Shell32.Shell();
Shell32.Folder destinationFolder = objShell.NameSpace(folderPath);
Shell32.Folder sourceFile = objShell.NameSpace(zipFile);
foreach (var file in sourceFile.Items())
destinationFolder.CopyHere(file, 4 | 16);
The usage is fairly simple:
UnZip(@"C:\myzipfile.zip", @"C:\my destination folder");
You may have noticed the 4 | 16 values in the CopyHere method. Those are the copy options which you can change to make the copying behave differently in order to suit your needs. Here is the list of the additional options.
4 – Do not display a progress dialog box.
8 – Give the file being operated on a new name in a move, copy, or rename operation if a file with the target name already exists.
16 – Respond with “Yes to All” for any dialog box that is displayed.
64 – Preserve undo information, if possible.
128 – Perform the operation on files only if a wildcard file name (*.*) is specified.
256 – Display a progress dialog box but do not show the file names.
512 – Do not confirm the creation of a new directory if the operation requires one to be created.
1024 – Do not display a user interface if an error occurs.
2048 – Version 4.71. Do not copy the security attributes of the file.
4096 – Only operate in the local directory. Do not operate recursively into subdirectories.
8192 – Version 5.0. Do not copy connected files as a group. Only copy the specified files.