Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / ATL

Quickly unzipping a file

4.80/5 (2 votes)
22 Jan 2014CPOL 13.3K  
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

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

And here is the function:

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

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

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

  // folder items inside the zip file
  CComPtr<folderitems> 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;
}
</folderitems></folder></folder></ishelldispatch>

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!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)