2010-05-26 26 views
6

我一直在尝试阅读卷影复制服务API函数的文档,目的是复制在Windows XP下当前被锁定(正在使用)的文件。C中的卷影复制服务(VSS)示例?

不幸的是,我似乎没有得到任何地方。任何人都碰巧有一个如何与API交互的代码示例,用于复制这些文件?

感谢,Doori酒吧

回答

4

我有过类似的麻烦,很多打了试验我已经成功地得到的地方后... 这里的代码片段可以帮助:

#include <stdio.h> 

#include <windows.h> 
#include <winbase.h> 

#include <Vss.h> 
#include <VsWriter.h> 
#include <VsBackup.h> 


int main() 
{ 
    int retCode = 0; 
    int i=0; 
    HRESULT hr; 
    IVssEnumObject *pIEnumSnapshots; 
    IVssBackupComponents *ab; 
    VSS_OBJECT_PROP Prop; 
    VSS_SNAPSHOT_PROP& Snap = Prop.Obj.Snap; 
    WCHAR existingFilePath[MAX_PATH] = TEXT("\\temp\\PrinterList.txt"); 
    WCHAR newFileLocation[MAX_PATH] = TEXT("c:\\Users\\PrinterList.txt"); 
    TCHAR existingFileLocation[MAX_PATH]; 

    if (CoInitialize(NULL) != S_OK) 
    { 
     printf("CoInitialize failed!\n"); 
     return 1; 
    } 

    hr = CreateVssBackupComponents(&ab); 
    if(hr != S_OK) 
    { 
     printf("Failed at CreateVssBackupComponents Stage"); 
     return 1; 
    } 

    hr = ab->InitializeForBackup(); 
    if(hr != S_OK) 
    { 
     printf("Failed at InitializeForBackup Stage"); 
     return 1; 
    } 

    hr = ab->SetContext(VSS_CTX_ALL); 
    if(hr != S_OK) 
    { 
     printf("Failed at SetContext Stage"); 
     return 1; 
    } 

    hr = ab->Query(GUID_NULL,VSS_OBJECT_NONE, VSS_OBJECT_SNAPSHOT, &pIEnumSnapshots); 
    if(hr != S_OK){ 
     printf("Failed at Query Stage"); 
     return 1; 
    } 

    // Enumerate all shadow copies. 
    printf("Recursing through snapshots...\n"); 
    while(true) 
    { 
     // Get the next element 
     ULONG ulFetched; 
     hr = pIEnumSnapshots->Next(1, &Prop, &ulFetched); 

     // We reached the end of list 
     if (ulFetched == 0) 
      break; 

     wprintf(L"Snapshot:%s\n", Snap.m_pwszSnapshotDeviceObject); 
     /* 
     At this point you have the Snap object with all the information required for copying the file. 
     example: 
     Snap.m_pwszSnapshotDeviceObject is the root for snapshot object 
     (like \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1) 
     Snap.m_pwszOriginalVolumeName is the full unicode name 
     (like \\?\Volume{1240872a-88de-11df-a94d-806e6f6e6963}\) 
     for the original root(c: mostly) 

     So, you can use CopyFile() to do what you want 
     */ 


     wcscpy(existingFileLocation, Snap.m_pwszSnapshotDeviceObject); 
     wcscat(existingFileLocation, existingFilePath); 
     CopyFile(existingFileLocation, newFileLocation, false); 
     //false here will enable over-write 
    } 
    return retCode; 
} 

注意:如果您的目标机器与生成机器不同,您需要包含正确的定义和生成配置。

注意:你将不得不在所有地方都使用恼人的wash,因为这些函数使用它们。

+0

对不起,迟到的回复,我想感谢你的样品 - 我希望它会帮助别人,因为它看起来不像C? – 2010-09-25 05:02:48

+0

实际上它是C,一些C++风格的定义是有误导性的。我将对其进行编辑并将其标准化为C(明天将有一个截止日期)。 – lalli 2010-09-25 17:14:48

+0

在这里你可以看到,它现在主要是C(当然还有win32,需要API)...... – lalli 2010-09-27 05:33:35