使用COM

时间:2015-09-03 10:25:40

标签: c++ com zip

我一直在寻找一种方法将文件压缩在一起以便由Web服务发送,然后在收到后将其提取出来。我找到了我在这里显示的代码http://www.codeproject.com/Articles/280650/Zip-Unzip-using-Windows-Shell。将文件放入zip文件夹的代码很好,即:

BSTR source = L"C:\\Users\\...\\Desktop\\test1.txt\0\0";
BSTR dest = L"C:\\Users\\...\\Desktop\\test.zip\\\0\0";

HRESULT hResult;
IShellDispatch *pISD;
Folder *pToFolder = NULL;
VARIANT vDir, vFile, vOpt;

CoInitialize(NULL);

hResult = CoCreateInstance
(CLSID_Shell, NULL, CLSCTX_INPROC_SERVER, IID_IShellDispatch, (void **)&pISD);

if (SUCCEEDED(hResult))
{
  VariantInit(&vDir);
  vDir.vt = VT_BSTR;
  vDir.bstrVal = dest;
  // Destination is our zip file
  hResult = pISD->NameSpace(vDir, &pToFolder);
  if (SUCCEEDED(hResult))
  {

     // Now copy source file(s) to the zip
     VariantInit(&vFile);
     vFile.vt = VT_BSTR;
     vFile.bstrVal = source;

     VariantInit(&vOpt);
     vOpt.vt = VT_I4;
     vOpt.lVal = FOF_NO_UI;

     // Copying and compressing the source files to our zip
     hResult = pToFolder->CopyHere(vFile, vOpt);

     Sleep(1000);
     pToFolder->Release();
   }
   pISD->Release();
}
CoUninitialize();

从zip文件中提取文件的代码不是,这就是:

BSTR source = L"C:\\Users\\...\\Desktop\\test1.zip\\\0\0";
BSTR dest = L"C:\\Users\\...\\Desktop\\unzipto\\\0\0";

HRESULT hResult;
IShellDispatch *pISD;
Folder *pToFolder = NULL;
VARIANT vDir, vFile, vOpt;

CoInitialize(NULL);

hResult = CoCreateInstance
(CLSID_Shell, NULL, CLSCTX_INPROC_SERVER, IID_IShellDispatch, (void **)&pISD);

if (SUCCEEDED(hResult))
{
  VariantInit(&vDir);
  vDir.vt = VT_BSTR;
  vDir.bstrVal = dest;
  // Destination is our zip file
  hResult = pISD->NameSpace(vDir, &pToFolder);
  if (SUCCEEDED(hResult))
  {
      Folder *pFromFolder = NULL;
      VariantInit(&vFile);
      vFile.vt = VT_BSTR;
      vFile.bstrVal = source;

      pISD->NameSpace(vFile, &pFromFolder);
      FolderItems *fi = NULL;
      pFromFolder->Items(&fi); //----Fails Here!-----

      VariantInit(&vOpt);
      vOpt.vt = VT_I4;
      vOpt.lVal = FOF_NO_UI; // Do not display a progress dialog box

      // Creating a new Variant with pointer to FolderItems to be copied
      VARIANT newV;
      VariantInit(&newV);
      newV.vt = VT_DISPATCH;
      newV.pdispVal = fi;

      hResult = pToFolder->CopyHere(newV, vOpt);
      Sleep(1000);
      pFromFolder->Release();
      pToFolder->Release();
    }
  pISD->Release();
}
CoUninitialize();

该程序在pFromFolder->Items(&fi);失败。

在运行程序之前,目标文件夹“unzipto”存在。还试图在“文件夹”变量上找到任何东西是非常棘手的,因为谷歌带回了所有我想要的东西。

有没有人可以对此有所了解,甚至可以告诉我为什么会发生这种情况?

1 个答案:

答案 0 :(得分:0)

好了几乎疯了,试图找出为什么这不起作用我意识到我的源文件有错误的文件名。我有test1.zip而不是test.zip,每次我阅读它都会错过它!很简单.......