2010-05-26 28 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