65.9K
CodeProject is changing. Read more.
Home

Quickly unzipping a file

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.80/5 (2 votes)

Jan 22, 2014

CPOL
viewsIcon

13342

How to use the shell to unzip a file to a folder location

Introduction

This is a small code snippet that uses the shell to unzip a zip-file. It is meant to to be used from your application if you need a simple, uncomplicated way to quickly unzip something, without the need to include other libraries or write lots of code. It is not meant to be a replacement for a complete, flexible solution that is able to deal with zip files in general. 

Honsestly, the code is not my idea. I found it on MSDN and I just adapted it to use ATL's save pointers and made it a bit more compact.

Using the code

Add the function to your application and just call

HRESULT hr = Unzip2Folder(aZIPFile, aDestinationFolder);
// error checking here

And here is the function:

HRESULT Unzip2Folder(LPCTSTR zipFileName, LPCTSTR outFolderName)
{
  // the shell object
  CComPtr shell;
  HRESULT hr = shell.CoCreateInstance(CLSID_Shell);
  if (FAILED(hr)) {
    return hr;
  }

  // the zip file
  CComPtr zipFile;
  hr = shell->NameSpace(CComVariant(zipFileName), &zipFile);
  if (FAILED(hr)) {
    return hr;
  }

  // destination folder
  CComPtr destination;
  hr = shell->NameSpace(CComVariant(outFolderName), &destination);
  if (FAILED(hr)) {
    return hr;
  }

  // folder items inside the zip file
  CComPtr folderItems;
  hr = zipFile->Items(&folderItems);
  if (FAILED(hr)) {
    return hr;
  }

  // copy operation
  hr = destination->CopyHere(CComVariant(folderItems),
      CComVariant(2048 | 1024 | 512 | 16 | 4, VT_I4));

  return hr;
}

If you need more information you should probably read about IShellDispatch, Folder and FolderItems.

For the flags used in CopyHere please look at Folder::CopyHere. Basically they supress all UIs that may appear. Depending on your application you might want to change this.

And that's all, folkes!