Sample code for 30+ languages & platforms
DataFlex Requires Chilkat v11.6.0+

OneDrive: Copy a File or Folder and Monitor Completion

See more OneDrive Examples

Creates a new item: copy a selected item to an explicitly addressed destination folder. A folder copy includes its descendants. The first run submits the request and saves its monitor URL; subsequent runs make one status request without submitting another copy. Use a fresh private receipt for each intentional operation and account. Schedule checks with backoff and honor Retry-After; 202 means accepted, not finished.

The receipt starts as pending before submission. A lost response or failed write requires reconciling the destination before starting again. Completed and failed receipts prevent automatic resubmission. Monitoring accepts JSON completion and 303 completion responses without automatically following redirects. A resourceId, when returned, is the new item ID and stays a string. Monitor URLs can expire; they are private, temporary operation state.

The default conflict behavior fails on a name collision. Copies inherit destination permissions and do not retain all source metadata. This example copies current content only. Copying all versions requires includeAllVersionHistory=true; Microsoft documents a current issue when it is combined with name, so copy first without name and rename afterward for that workflow. Folder copies are limited to 30,000 items; app-only cross-geo copy is unsupported.

Microsoft has announced changes to preauthenticated URLs beginning April 1, 2027. The example supports Graph-hosted URLs with the Graph token and an explicitly configured SharePoint host with a separate SharePoint-audience token. A legacy preauthenticated URL is requested without a bearer token. Never forward the Graph token to a SharePoint or content host. If required, prepare private qa_data/tokens/oneDrive-sharepoint.json with host and access_token from a separately authorized SharePoint token acquisition; token refresh must preserve that audience. A 401 requires checking the correct token audience or URL expiry, not blindly adding credentials.

Permission: Files.ReadWrite.

Uses direct Chilkat.Http requests to Microsoft Graph v1.0 in the global cloud. The delegated token is read from the private qa_data/tokens/oneDrive.json file created by the PKCE authorization example. Personal Microsoft accounts and Microsoft 365 work/school accounts can use delegated authorization when the app registration supports them. Refresh expired tokens; scopes and actual file access both matter.

For app-only Microsoft 365 access, use client credentials with administrator-approved application permissions. /me requires a signed-in user; app-only calls must address an authorized user, site, or drive explicitly. Client credentials do not grant access to personal OneDrive accounts. National clouds use their own authority and Graph hosts.

Check the expected HTTP status before using a response body. A false method result can still contain an HTTP error response; status zero means no response arrived. For 401, renew authorization; for 403, check permissions, access grants, and policy; for 429, honor Retry-After with a bounded retry. Reconcile uncertain writes before repeating them. Keep credentials, file contents, upload/download URLs, and detailed diagnostics private.

Microsoft documentation

Chilkat DataFlex Downloads

DataFlex
Use ChilkatAx-win32.pkg

Procedure Test
    Boolean iSuccess
    Handle hoToken
    Handle hoHttp
    Variant vResp
    Handle hoResp
    Handle hoResult
    String sDriveId
    String sItemId
    Handle hoEndpoint
    String sDestinationDriveId
    String sDestinationFolderId
    String sNewName
    String sAccountKey
    String sReceiptPath
    Handle hoFac
    Handle hoReceipt
    Variant vBody
    Handle hoBody
    String sMonitorUrl
    String sStatusUrl
    Handle hoServiceUrl
    Handle hoMonitorHttp
    Handle hoServiceHost
Files    Handle hoTokenFiles
    Handle hoSharepointToken
    Boolean iCompleted
    String sTemp1
    String sTemp2
    String sTemp3
    Integer iTemp1
    Integer iTemp2
    Integer iTemp3
    Boolean bTemp1

    Move False To iSuccess

    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    Move False To iSuccess
    //  Obtain a delegated Graph token with this example's file permissions.
    //  See OneDrive OAuth2 with PKCE.
    Get Create (RefClass(cComChilkatJsonObject)) To hoToken
    If (Not(IsComObjectCreated(hoToken))) Begin
        Send CreateComObject of hoToken
    End
    Set ComStrict Of hoToken To True
    Get ComLoadFile Of hoToken "qa_data/tokens/oneDrive.json" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not load the private OneDrive token cache."
        Procedure_Return
    End

    Get ComJsonTypeOf Of hoToken "access_token" To iTemp1
    Get ComStringOfEquals Of hoToken "access_token" "" True To bTemp1
    If ((iTemp1 <> 1) Or (bTemp1 = True)) Begin
        Showln "Expected a nonempty access_token in the JSON."
        Procedure_Return
    End

    Get Create (RefClass(cComChilkatHttp)) To hoHttp
    If (Not(IsComObjectCreated(hoHttp))) Begin
        Send CreateComObject of hoHttp
    End
    Get ComStringOf Of hoToken "access_token" To sTemp1
    Set ComAuthToken Of hoHttp To sTemp1
    Set ComRequireSslCertVerify Of hoHttp To True
    Set ComFollowRedirects Of hoHttp To False
    Set ComConnectTimeout Of hoHttp To 20
    Set ComReadTimeout Of hoHttp To 120
    Send ComSetRequestHeader To hoHttp "Accept" "application/json"
    Get Create (RefClass(cComChilkatHttpResponse)) To hoResp
    If (Not(IsComObjectCreated(hoResp))) Begin
        Send CreateComObject of hoResp
    End
    Get Create (RefClass(cComChilkatJsonObject)) To hoResult
    If (Not(IsComObjectCreated(hoResult))) Begin
        Send CreateComObject of hoResult
    End
    Set ComStrict Of hoResult To True
    Move "YOUR_DRIVE_ID" To sDriveId
    Move "YOUR_ITEM_ID" To sItemId
    Get Create (RefClass(cComChilkatStringBuilder)) To hoEndpoint
    If (Not(IsComObjectCreated(hoEndpoint))) Begin
        Send CreateComObject of hoEndpoint
    End
    Get ComAppend Of hoEndpoint "https://graph.microsoft.com/v1.0/drives/" To iSuccess
    Get ComUrlEncode Of hoHttp sDriveId To sTemp1
    Get ComAppend Of hoEndpoint sTemp1 To iSuccess
    Get ComAppend Of hoEndpoint "/items/" To iSuccess
    Get ComUrlEncode Of hoHttp sItemId To sTemp1
    Get ComAppend Of hoEndpoint sTemp1 To iSuccess
    Move "YOUR_DESTINATION_DRIVE_ID" To sDestinationDriveId
    Move "YOUR_DESTINATION_FOLDER_ID" To sDestinationFolderId
    Move "copied-file.txt" To sNewName
    //  Use a separate private receipt for each copy operation and account.
    Move "YOUR_LOCAL_ACCOUNT_KEY" To sAccountKey
    Move "qa_data/oneDrive/copy-receipt.json" To sReceiptPath
    Get Create (RefClass(cComCkFileAccess)) To hoFac
    If (Not(IsComObjectCreated(hoFac))) Begin
        Send CreateComObject of hoFac
    End
    Get ComDirEnsureExists Of hoFac "qa_data/oneDrive" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not create the private receipt directory."
        Procedure_Return
    End

    Get Create (RefClass(cComChilkatJsonObject)) To hoReceipt
    If (Not(IsComObjectCreated(hoReceipt))) Begin
        Send CreateComObject of hoReceipt
    End
    Set ComStrict Of hoReceipt To True
    Get ComFileExists Of hoFac sReceiptPath To bTemp1
    If (bTemp1 = True) Begin
        Get ComLoadFile Of hoReceipt sReceiptPath To iSuccess
        If (iSuccess <> True) Begin
            Showln "Invalid receipt; reconcile the existing operation before starting another."
            Procedure_Return
        End

        Get ComStringOfEquals Of hoReceipt "accountKey" sAccountKey True To bTemp1
        If (bTemp1 <> True) Begin
            Showln "Receipt belongs to another copy operation; no request sent."
            Procedure_Return
        End

        Get ComStringOfEquals Of hoReceipt "sourceDriveId" sDriveId True To bTemp1
        If (bTemp1 <> True) Begin
            Showln "Receipt belongs to another copy operation; no request sent."
            Procedure_Return
        End

        Get ComStringOfEquals Of hoReceipt "sourceItemId" sItemId True To bTemp1
        If (bTemp1 <> True) Begin
            Showln "Receipt belongs to another copy operation; no request sent."
            Procedure_Return
        End

        Get ComStringOfEquals Of hoReceipt "destinationDriveId" sDestinationDriveId True To bTemp1
        If (bTemp1 <> True) Begin
            Showln "Receipt belongs to another copy operation; no request sent."
            Procedure_Return
        End

        Get ComStringOfEquals Of hoReceipt "destinationFolderId" sDestinationFolderId True To bTemp1
        If (bTemp1 <> True) Begin
            Showln "Receipt belongs to another copy operation; no request sent."
            Procedure_Return
        End

        Get ComStringOfEquals Of hoReceipt "name" sNewName True To bTemp1
        If (bTemp1 <> True) Begin
            Showln "Receipt belongs to another copy operation; no request sent."
            Procedure_Return
        End

        Get ComStringOfEquals Of hoReceipt "status" "completed" True To bTemp1
        If (bTemp1 = True) Begin
            Get ComStringOf Of hoReceipt "resourceId" To sTemp1
            Showln "This copy already completed. Item ID: " sTemp1
            Procedure_Return
        End

        Get ComStringOfEquals Of hoReceipt "status" "failed" True To bTemp1
        If (bTemp1 = True) Begin
            Showln "The saved copy failed. Review its error and destination before starting another operation."
            Procedure_Return
        End

        Get ComStringOfEquals Of hoReceipt "status" "monitoring" True To bTemp1
        If (bTemp1 <> True) Begin
            Showln "Copy outcome is uncertain; reconcile the destination before replacing this receipt."
            Procedure_Return
        End

        Get ComJsonTypeOf Of hoReceipt "monitorUrl" To iTemp1
        Get ComStringOfEquals Of hoReceipt "monitorUrl" "" True To bTemp1
        If ((iTemp1 <> 1) Or (bTemp1 = True)) Begin
            Showln "Expected a nonempty monitorUrl in the JSON."
            Procedure_Return
        End

    End
    Else Begin
        Get ComUpdateString Of hoReceipt "accountKey" sAccountKey To iSuccess
        Get ComUpdateString Of hoReceipt "sourceDriveId" sDriveId To iSuccess
        Get ComUpdateString Of hoReceipt "sourceItemId" sItemId To iSuccess
        Get ComUpdateString Of hoReceipt "destinationDriveId" sDestinationDriveId To iSuccess
        Get ComUpdateString Of hoReceipt "destinationFolderId" sDestinationFolderId To iSuccess
        Get ComUpdateString Of hoReceipt "name" sNewName To iSuccess
        //  Save intent before POST so a lost response cannot cause an automatic duplicate copy.
        Get ComUpdateString Of hoReceipt "status" "pending" To iSuccess
        Get ComWriteFile Of hoReceipt sReceiptPath To iSuccess
        If (iSuccess <> True) Begin
            Showln "Could not save the copy intent; nothing submitted."
            Procedure_Return
        End

        Get Create (RefClass(cComChilkatJsonObject)) To hoBody
        If (Not(IsComObjectCreated(hoBody))) Begin
            Send CreateComObject of hoBody
        End
        Get ComUpdateString Of hoBody "parentReference.driveId" sDestinationDriveId To iSuccess
        Get ComUpdateString Of hoBody "parentReference.id" sDestinationFolderId To iSuccess
        Get ComUpdateString Of hoBody "name" sNewName To iSuccess
        Get ComAppend Of hoEndpoint "/copy" To iSuccess
        //  Omit conflictBehavior: the default is fail, and the query option is not supported by personal OneDrive.
        Get ComGetAsString Of hoEndpoint To sTemp1
        Get pvComObject of hoBody to vBody
        Get pvComObject of hoResp to vResp
        Get ComHttpJson Of hoHttp "POST" sTemp1 vBody "application/json" vResp To iSuccess
        Get ComStatusCode Of hoResp To iTemp1
        If ((iSuccess <> True) And (iTemp1 = 0)) Begin
            Showln "No HTTP response received; inspect diagnostics privately and reconcile writes before retrying."
            Procedure_Return
        End

        Get ComStatusCode Of hoResp To iTemp1
        If ((iTemp1 <> 202)) Begin
            Get ComStatusCode Of hoResp To iTemp1
            Showln "Unexpected HTTP status: " iTemp1
            Get ComGetHeaderField Of hoResp "request-id" To sTemp1
            Showln "Request ID: " sTemp1
            Get ComStatusCode Of hoResp To iTemp1
            If (iTemp1 = 429) Begin
                Get ComGetHeaderField Of hoResp "Retry-After" To sTemp1
                Showln "Retry-After: " sTemp1
            End

            Procedure_Return
        End

        Get ComGetHeaderField Of hoResp "Location" To sMonitorUrl
        If (sMonitorUrl = "") Begin
            Showln "Accepted without a monitor URL; keep the pending receipt and reconcile the destination."
            Procedure_Return
        End

        Get ComUpdateString Of hoReceipt "monitorUrl" sMonitorUrl To iSuccess
        Get ComUpdateString Of hoReceipt "status" "monitoring" To iSuccess
        Get ComWriteFile Of hoReceipt sReceiptPath To iSuccess
        If (iSuccess <> True) Begin
            Showln "Accepted, but receipt save failed. Do not repeat POST; reconcile the destination."
            Procedure_Return
        End

        Showln "Copy accepted. Run again later to check its status; honor Retry-After."
        Get ComGetHeaderField Of hoResp "Retry-After" To sTemp1
        Showln "Retry-After: " sTemp1
        Procedure_Return
    End

    //  One status request per run. The caller schedules the next run with backoff and Retry-After.
    Get ComStringOf Of hoReceipt "monitorUrl" To sStatusUrl
    Get Create (RefClass(cComChilkatUrl)) To hoServiceUrl
    If (Not(IsComObjectCreated(hoServiceUrl))) Begin
        Send CreateComObject of hoServiceUrl
    End
    Get ComParseUrl Of hoServiceUrl sStatusUrl To iSuccess
    If (iSuccess <> True) Begin
        Showln "Invalid service URL."
        Procedure_Return
    End

    Get ComSsl Of hoServiceUrl To bTemp1
    Get ComHost Of hoServiceUrl To sTemp1
    Get ComLogin Of hoServiceUrl To sTemp2
    Get ComPassword Of hoServiceUrl To sTemp3
    If ((bTemp1 <> True) Or (sTemp1 = "") Or (sTemp2 <> "") Or (sTemp3 <> "")) Begin
        Showln "Expected an HTTPS service URL without embedded login credentials."
        Procedure_Return
    End

    Get Create (RefClass(cComChilkatHttp)) To hoMonitorHttp
    If (Not(IsComObjectCreated(hoMonitorHttp))) Begin
        Send CreateComObject of hoMonitorHttp
    End
    Set ComRequireSslCertVerify Of hoMonitorHttp To True
    Set ComFollowRedirects Of hoMonitorHttp To False
    Set ComConnectTimeout Of hoMonitorHttp To 20
    Set ComReadTimeout Of hoMonitorHttp To 120
    Get Create (RefClass(cComChilkatStringBuilder)) To hoServiceHost
    If (Not(IsComObjectCreated(hoServiceHost))) Begin
        Send CreateComObject of hoServiceHost
    End
    Get ComHost Of hoServiceUrl To sTemp1
    Get ComAppend Of hoServiceHost sTemp1 To iSuccess
    Get ComContentsEqual Of hoServiceHost "graph.microsoft.com" False To bTemp1
    Get ComPort Of hoServiceUrl To iTemp1
    If ((bTemp1 = True) And (iTemp1 = 443)) Begin
        Get ComStringOf Of hoToken "access_token" To sTemp1
        Set ComAuthToken Of hoMonitorHttp To sTemp1
    End
    Else Begin
        Get Create (RefClass(cComCkFileAccess)) To hoTokenFiles
        If (Not(IsComObjectCreated(hoTokenFiles))) Begin
            Send CreateComObject of hoTokenFiles
        End
        Get ComFileExists Of hoTokenFiles "qa_data/tokens/oneDrive-sharepoint.json" To bTemp1
        If (bTemp1 = True) Begin
            Get Create (RefClass(cComChilkatJsonObject)) To hoSharepointToken
            If (Not(IsComObjectCreated(hoSharepointToken))) Begin
                Send CreateComObject of hoSharepointToken
            End
            Set ComStrict Of hoSharepointToken To True
            Get ComLoadFile Of hoSharepointToken "qa_data/tokens/oneDrive-sharepoint.json" To iSuccess
            If (iSuccess <> True) Begin
                Showln "Could not read the private SharePoint token cache."
                Procedure_Return
            End

            Get ComJsonTypeOf Of hoSharepointToken "host" To iTemp1
            Get ComStringOfEquals Of hoSharepointToken "host" "" True To bTemp1
            If ((iTemp1 <> 1) Or (bTemp1 = True)) Begin
                Showln "Expected a nonempty host in the JSON."
                Procedure_Return
            End

            Get ComJsonTypeOf Of hoSharepointToken "access_token" To iTemp1
            Get ComStringOfEquals Of hoSharepointToken "access_token" "" True To bTemp1
            If ((iTemp1 <> 1) Or (bTemp1 = True)) Begin
                Showln "Expected a nonempty access_token in the JSON."
                Procedure_Return
            End

            //  host is a configured exact hostname, not a URL and not obtained from the service response.
            Get ComContentsEqual Of hoServiceHost (ComStringOf(hoSharepointToken, "host")) False To bTemp1
            Get ComPort Of hoServiceUrl To iTemp1
            If ((bTemp1 = True) And (iTemp1 = 443)) Begin
                Get ComStringOf Of hoSharepointToken "access_token" To sTemp1
                Set ComAuthToken Of hoMonitorHttp To sTemp1
            End

        End

    End

    //  With no matching token configured, only a still-valid preauthenticated URL can succeed.
    Get pvComObject of hoResp to vResp
    Get ComHttpNoBody Of hoMonitorHttp "GET" sStatusUrl vResp To iSuccess
    Get ComStatusCode Of hoResp To iTemp1
    If ((iSuccess <> True) And (iTemp1 = 0)) Begin
        Showln "No HTTP response received; inspect diagnostics privately and reconcile writes before retrying."
        Procedure_Return
    End

    Get ComStatusCode Of hoResp To iTemp1
    Get ComStatusCode Of hoResp To iTemp2
    Get ComStatusCode Of hoResp To iTemp3
    If ((iTemp1 <> 200) And (iTemp2 <> 202) And (iTemp3 <> 303)) Begin
        Get ComStatusCode Of hoResp To iTemp1
        Showln "Unexpected HTTP status: " iTemp1
        Get ComGetHeaderField Of hoResp "request-id" To sTemp1
        Showln "Request ID: " sTemp1
        Get ComStatusCode Of hoResp To iTemp1
        If (iTemp1 = 429) Begin
            Get ComGetHeaderField Of hoResp "Retry-After" To sTemp1
            Showln "Retry-After: " sTemp1
        End

        Procedure_Return
    End

    Get ComStatusCode Of hoResp To iTemp1
    Move (iTemp1 = 303) To iCompleted
    Get ComBodyStr Of hoResp To sTemp1
    If (sTemp1 <> "") Begin
        Get ComBodyStr Of hoResp To sTemp1
        Get ComLoad Of hoResult sTemp1 To iSuccess
        If (iSuccess <> True) Begin
            Showln "Invalid monitor JSON; keep the receipt and inspect the operation."
            Procedure_Return
        End

        Get ComStringOfEquals Of hoResult "status" "completed" False To bTemp1
        If (bTemp1 = True) Begin
            Move True To iCompleted
        End

        Get ComStringOfEquals Of hoResult "status" "failed" False To bTemp1
        If (bTemp1 = True) Begin
            Get ComUpdateString Of hoReceipt "status" "failed" To iSuccess
            Get ComStringOf Of hoResult "error.code" To sTemp1
            Get ComUpdateString Of hoReceipt "errorCode" sTemp1 To iSuccess
            Get ComWriteFile Of hoReceipt sReceiptPath To iSuccess
            If (iSuccess <> True) Begin
                Showln "Could not save the failed-operation receipt."
                Procedure_Return
            End

            Get ComStringOf Of hoResult "error.code" To sTemp1
            Showln "Copy failed: " sTemp1
            Procedure_Return
        End

    End

    If (iCompleted = True) Begin
        Get ComUpdateString Of hoReceipt "status" "completed" To iSuccess
        Get ComJsonTypeOf Of hoResult "resourceId" To iTemp1
        If (iTemp1 = 1) Begin
            Get ComStringOf Of hoResult "resourceId" To sTemp1
            Get ComUpdateString Of hoReceipt "resourceId" sTemp1 To iSuccess
        End

        Get ComWriteFile Of hoReceipt sReceiptPath To iSuccess
        If (iSuccess <> True) Begin
            Showln "Copy completed but the receipt could not be saved. Reconcile before another copy."
            Procedure_Return
        End

        Showln "Copy completed. Destination drive ID: " sDestinationDriveId
        Get ComStringOf Of hoReceipt "resourceId" To sTemp1
        Showln "New item ID, if returned: " sTemp1
        //  A 303 without a JSON resourceId still indicates completion. Look up the destination by name if needed.
        //  Do not follow Location/resourceLocation with the Graph bearer token automatically.
    End
    Else Begin
        Get ComStringOf Of hoResult "status" To sTemp1
        Showln "Copy not completed. Status: " sTemp1
        Get ComStringOf Of hoResult "percentageComplete" To sTemp1
        Showln "Percent complete, if returned: " sTemp1
        Get ComGetHeaderField Of hoResp "Retry-After" To sTemp1
        Showln "Retry-After: " sTemp1
    End



End_Procedure