Sample code for 30+ languages & platforms
Visual FoxPro 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 Visual FoxPro Downloads

Visual FoxPro
LOCAL lnSuccess
LOCAL loToken
LOCAL loHttp
LOCAL loResp
LOCAL loResult
LOCAL lcDriveId
LOCAL lcItemId
LOCAL loEndpoint
LOCAL lcDestinationDriveId
LOCAL lcDestinationFolderId
LOCAL lcNewName
LOCAL lcAccountKey
LOCAL lcReceiptPath
LOCAL loFac
LOCAL loReceipt
LOCAL loBody
LOCAL lcMonitorUrl
LOCAL lcStatusUrl
LOCAL loServiceUrl
LOCAL loMonitorHttp
LOCAL loServiceHost
LOCAL loTokenFiles
LOCAL loSharepointToken
LOCAL lnCompleted

lnSuccess = 0

*  Assumes Chilkat is unlocked. See Global Unlock Sample.
lnSuccess = 0
*  Obtain a delegated Graph token with this example's file permissions.
*  See OneDrive OAuth2 with PKCE.
loToken = CreateObject('Chilkat.JsonObject')
loToken.Strict = 1
lnSuccess = loToken.LoadFile("qa_data/tokens/oneDrive.json")
IF (lnSuccess <> 1) THEN
    ? "Could not load the private OneDrive token cache."
    RELEASE loToken
    CANCEL
ENDIF

IF ((loToken.JsonTypeOf("access_token") <> 1) OR (loToken.StringOfEquals("access_token","",1) = 1)) THEN
    ? "Expected a nonempty access_token in the JSON."
    RELEASE loToken
    CANCEL
ENDIF

loHttp = CreateObject('Chilkat.Http')
loHttp.AuthToken = loToken.StringOf("access_token")
loHttp.RequireSslCertVerify = 1
loHttp.FollowRedirects = 0
loHttp.ConnectTimeout = 20
loHttp.ReadTimeout = 120
loHttp.SetRequestHeader("Accept","application/json")
loResp = CreateObject('Chilkat.HttpResponse')
loResult = CreateObject('Chilkat.JsonObject')
loResult.Strict = 1
lcDriveId = "YOUR_DRIVE_ID"
lcItemId = "YOUR_ITEM_ID"
loEndpoint = CreateObject('Chilkat.StringBuilder')
loEndpoint.Append("https://graph.microsoft.com/v1.0/drives/")
loEndpoint.Append(loHttp.UrlEncode(lcDriveId))
loEndpoint.Append("/items/")
loEndpoint.Append(loHttp.UrlEncode(lcItemId))
lcDestinationDriveId = "YOUR_DESTINATION_DRIVE_ID"
lcDestinationFolderId = "YOUR_DESTINATION_FOLDER_ID"
lcNewName = "copied-file.txt"
*  Use a separate private receipt for each copy operation and account.
lcAccountKey = "YOUR_LOCAL_ACCOUNT_KEY"
lcReceiptPath = "qa_data/oneDrive/copy-receipt.json"
loFac = CreateObject('Chilkat.FileAccess')
lnSuccess = loFac.DirEnsureExists("qa_data/oneDrive")
IF (lnSuccess <> 1) THEN
    ? "Could not create the private receipt directory."
    RELEASE loToken
    RELEASE loHttp
    RELEASE loResp
    RELEASE loResult
    RELEASE loEndpoint
    RELEASE loFac
    CANCEL
ENDIF

loReceipt = CreateObject('Chilkat.JsonObject')
loReceipt.Strict = 1
IF (loFac.FileExists(lcReceiptPath) = 1) THEN
    lnSuccess = loReceipt.LoadFile(lcReceiptPath)
    IF (lnSuccess <> 1) THEN
        ? "Invalid receipt; reconcile the existing operation before starting another."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loEndpoint
        RELEASE loFac
        RELEASE loReceipt
        CANCEL
    ENDIF

    IF (loReceipt.StringOfEquals("accountKey",lcAccountKey,1) <> 1) THEN
        ? "Receipt belongs to another copy operation; no request sent."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loEndpoint
        RELEASE loFac
        RELEASE loReceipt
        CANCEL
    ENDIF

    IF (loReceipt.StringOfEquals("sourceDriveId",lcDriveId,1) <> 1) THEN
        ? "Receipt belongs to another copy operation; no request sent."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loEndpoint
        RELEASE loFac
        RELEASE loReceipt
        CANCEL
    ENDIF

    IF (loReceipt.StringOfEquals("sourceItemId",lcItemId,1) <> 1) THEN
        ? "Receipt belongs to another copy operation; no request sent."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loEndpoint
        RELEASE loFac
        RELEASE loReceipt
        CANCEL
    ENDIF

    IF (loReceipt.StringOfEquals("destinationDriveId",lcDestinationDriveId,1) <> 1) THEN
        ? "Receipt belongs to another copy operation; no request sent."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loEndpoint
        RELEASE loFac
        RELEASE loReceipt
        CANCEL
    ENDIF

    IF (loReceipt.StringOfEquals("destinationFolderId",lcDestinationFolderId,1) <> 1) THEN
        ? "Receipt belongs to another copy operation; no request sent."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loEndpoint
        RELEASE loFac
        RELEASE loReceipt
        CANCEL
    ENDIF

    IF (loReceipt.StringOfEquals("name",lcNewName,1) <> 1) THEN
        ? "Receipt belongs to another copy operation; no request sent."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loEndpoint
        RELEASE loFac
        RELEASE loReceipt
        CANCEL
    ENDIF

    IF (loReceipt.StringOfEquals("status","completed",1) = 1) THEN
        ? "This copy already completed. Item ID: " + loReceipt.StringOf("resourceId")
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loEndpoint
        RELEASE loFac
        RELEASE loReceipt
        CANCEL
    ENDIF

    IF (loReceipt.StringOfEquals("status","failed",1) = 1) THEN
        ? "The saved copy failed. Review its error and destination before starting another operation."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loEndpoint
        RELEASE loFac
        RELEASE loReceipt
        CANCEL
    ENDIF

    IF (loReceipt.StringOfEquals("status","monitoring",1) <> 1) THEN
        ? "Copy outcome is uncertain; reconcile the destination before replacing this receipt."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loEndpoint
        RELEASE loFac
        RELEASE loReceipt
        CANCEL
    ENDIF

    IF ((loReceipt.JsonTypeOf("monitorUrl") <> 1) OR (loReceipt.StringOfEquals("monitorUrl","",1) = 1)) THEN
        ? "Expected a nonempty monitorUrl in the JSON."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loEndpoint
        RELEASE loFac
        RELEASE loReceipt
        CANCEL
    ENDIF

ELSE
    loReceipt.UpdateString("accountKey",lcAccountKey)
    loReceipt.UpdateString("sourceDriveId",lcDriveId)
    loReceipt.UpdateString("sourceItemId",lcItemId)
    loReceipt.UpdateString("destinationDriveId",lcDestinationDriveId)
    loReceipt.UpdateString("destinationFolderId",lcDestinationFolderId)
    loReceipt.UpdateString("name",lcNewName)
    *  Save intent before POST so a lost response cannot cause an automatic duplicate copy.
    loReceipt.UpdateString("status","pending")
    lnSuccess = loReceipt.WriteFile(lcReceiptPath)
    IF (lnSuccess <> 1) THEN
        ? "Could not save the copy intent; nothing submitted."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loEndpoint
        RELEASE loFac
        RELEASE loReceipt
        CANCEL
    ENDIF

    loBody = CreateObject('Chilkat.JsonObject')
    loBody.UpdateString("parentReference.driveId",lcDestinationDriveId)
    loBody.UpdateString("parentReference.id",lcDestinationFolderId)
    loBody.UpdateString("name",lcNewName)
    loEndpoint.Append("/copy")
    *  Omit conflictBehavior: the default is fail, and the query option is not supported by personal OneDrive.
    lnSuccess = loHttp.HttpJson("POST",loEndpoint.GetAsString(),loBody,"application/json",loResp)
    IF ((lnSuccess <> 1) AND (loResp.StatusCode = 0)) THEN
        ? "No HTTP response received; inspect diagnostics privately and reconcile writes before retrying."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loEndpoint
        RELEASE loFac
        RELEASE loReceipt
        RELEASE loBody
        CANCEL
    ENDIF

    IF ((loResp.StatusCode <> 202)) THEN
        ? "Unexpected HTTP status: " + STR(loResp.StatusCode)
        ? "Request ID: " + loResp.GetHeaderField("request-id")
        IF (loResp.StatusCode = 429) THEN
            ? "Retry-After: " + loResp.GetHeaderField("Retry-After")
        ENDIF

        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loEndpoint
        RELEASE loFac
        RELEASE loReceipt
        RELEASE loBody
        CANCEL
    ENDIF

    lcMonitorUrl = loResp.GetHeaderField("Location")
    IF (lcMonitorUrl = "") THEN
        ? "Accepted without a monitor URL; keep the pending receipt and reconcile the destination."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loEndpoint
        RELEASE loFac
        RELEASE loReceipt
        RELEASE loBody
        CANCEL
    ENDIF

    loReceipt.UpdateString("monitorUrl",lcMonitorUrl)
    loReceipt.UpdateString("status","monitoring")
    lnSuccess = loReceipt.WriteFile(lcReceiptPath)
    IF (lnSuccess <> 1) THEN
        ? "Accepted, but receipt save failed. Do not repeat POST; reconcile the destination."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loEndpoint
        RELEASE loFac
        RELEASE loReceipt
        RELEASE loBody
        CANCEL
    ENDIF

    ? "Copy accepted. Run again later to check its status; honor Retry-After."
    ? "Retry-After: " + loResp.GetHeaderField("Retry-After")
    RELEASE loToken
    RELEASE loHttp
    RELEASE loResp
    RELEASE loResult
    RELEASE loEndpoint
    RELEASE loFac
    RELEASE loReceipt
    RELEASE loBody
    CANCEL
ENDIF

*  One status request per run. The caller schedules the next run with backoff and Retry-After.
lcStatusUrl = loReceipt.StringOf("monitorUrl")
loServiceUrl = CreateObject('Chilkat.Url')
lnSuccess = loServiceUrl.ParseUrl(lcStatusUrl)
IF (lnSuccess <> 1) THEN
    ? "Invalid service URL."
    RELEASE loToken
    RELEASE loHttp
    RELEASE loResp
    RELEASE loResult
    RELEASE loEndpoint
    RELEASE loFac
    RELEASE loReceipt
    RELEASE loBody
    RELEASE loServiceUrl
    CANCEL
ENDIF

IF ((loServiceUrl.Ssl <> 1) OR (loServiceUrl.Host = "") OR (loServiceUrl.Login <> "") OR (loServiceUrl.Password <> "")) THEN
    ? "Expected an HTTPS service URL without embedded login credentials."
    RELEASE loToken
    RELEASE loHttp
    RELEASE loResp
    RELEASE loResult
    RELEASE loEndpoint
    RELEASE loFac
    RELEASE loReceipt
    RELEASE loBody
    RELEASE loServiceUrl
    CANCEL
ENDIF

loMonitorHttp = CreateObject('Chilkat.Http')
loMonitorHttp.RequireSslCertVerify = 1
loMonitorHttp.FollowRedirects = 0
loMonitorHttp.ConnectTimeout = 20
loMonitorHttp.ReadTimeout = 120
loServiceHost = CreateObject('Chilkat.StringBuilder')
loServiceHost.Append(loServiceUrl.Host)
IF ((loServiceHost.ContentsEqual("graph.microsoft.com",0) = 1) AND (loServiceUrl.Port = 443)) THEN
    loMonitorHttp.AuthToken = loToken.StringOf("access_token")
ELSE
    loTokenFiles = CreateObject('Chilkat.FileAccess')
    IF (loTokenFiles.FileExists("qa_data/tokens/oneDrive-sharepoint.json") = 1) THEN
        loSharepointToken = CreateObject('Chilkat.JsonObject')
        loSharepointToken.Strict = 1
        lnSuccess = loSharepointToken.LoadFile("qa_data/tokens/oneDrive-sharepoint.json")
        IF (lnSuccess <> 1) THEN
            ? "Could not read the private SharePoint token cache."
            RELEASE loToken
            RELEASE loHttp
            RELEASE loResp
            RELEASE loResult
            RELEASE loEndpoint
            RELEASE loFac
            RELEASE loReceipt
            RELEASE loBody
            RELEASE loServiceUrl
            RELEASE loMonitorHttp
            RELEASE loServiceHost
            RELEASE loTokenFiles
            RELEASE loSharepointToken
            CANCEL
        ENDIF

        IF ((loSharepointToken.JsonTypeOf("host") <> 1) OR (loSharepointToken.StringOfEquals("host","",1) = 1)) THEN
            ? "Expected a nonempty host in the JSON."
            RELEASE loToken
            RELEASE loHttp
            RELEASE loResp
            RELEASE loResult
            RELEASE loEndpoint
            RELEASE loFac
            RELEASE loReceipt
            RELEASE loBody
            RELEASE loServiceUrl
            RELEASE loMonitorHttp
            RELEASE loServiceHost
            RELEASE loTokenFiles
            RELEASE loSharepointToken
            CANCEL
        ENDIF

        IF ((loSharepointToken.JsonTypeOf("access_token") <> 1) OR (loSharepointToken.StringOfEquals("access_token","",1) = 1)) THEN
            ? "Expected a nonempty access_token in the JSON."
            RELEASE loToken
            RELEASE loHttp
            RELEASE loResp
            RELEASE loResult
            RELEASE loEndpoint
            RELEASE loFac
            RELEASE loReceipt
            RELEASE loBody
            RELEASE loServiceUrl
            RELEASE loMonitorHttp
            RELEASE loServiceHost
            RELEASE loTokenFiles
            RELEASE loSharepointToken
            CANCEL
        ENDIF

        *  host is a configured exact hostname, not a URL and not obtained from the service response.
        IF ((loServiceHost.ContentsEqual(loSharepointToken.StringOf("host"),0) = 1) AND (loServiceUrl.Port = 443)) THEN
            loMonitorHttp.AuthToken = loSharepointToken.StringOf("access_token")
        ENDIF

    ENDIF

ENDIF

*  With no matching token configured, only a still-valid preauthenticated URL can succeed.
lnSuccess = loMonitorHttp.HttpNoBody("GET",lcStatusUrl,loResp)
IF ((lnSuccess <> 1) AND (loResp.StatusCode = 0)) THEN
    ? "No HTTP response received; inspect diagnostics privately and reconcile writes before retrying."
    RELEASE loToken
    RELEASE loHttp
    RELEASE loResp
    RELEASE loResult
    RELEASE loEndpoint
    RELEASE loFac
    RELEASE loReceipt
    RELEASE loBody
    RELEASE loServiceUrl
    RELEASE loMonitorHttp
    RELEASE loServiceHost
    RELEASE loTokenFiles
    RELEASE loSharepointToken
    CANCEL
ENDIF

IF ((loResp.StatusCode <> 200) AND (loResp.StatusCode <> 202) AND (loResp.StatusCode <> 303)) THEN
    ? "Unexpected HTTP status: " + STR(loResp.StatusCode)
    ? "Request ID: " + loResp.GetHeaderField("request-id")
    IF (loResp.StatusCode = 429) THEN
        ? "Retry-After: " + loResp.GetHeaderField("Retry-After")
    ENDIF

    RELEASE loToken
    RELEASE loHttp
    RELEASE loResp
    RELEASE loResult
    RELEASE loEndpoint
    RELEASE loFac
    RELEASE loReceipt
    RELEASE loBody
    RELEASE loServiceUrl
    RELEASE loMonitorHttp
    RELEASE loServiceHost
    RELEASE loTokenFiles
    RELEASE loSharepointToken
    CANCEL
ENDIF

lnCompleted = loResp.StatusCode = 303
IF (loResp.BodyStr <> "") THEN
    lnSuccess = loResult.Load(loResp.BodyStr)
    IF (lnSuccess <> 1) THEN
        ? "Invalid monitor JSON; keep the receipt and inspect the operation."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loEndpoint
        RELEASE loFac
        RELEASE loReceipt
        RELEASE loBody
        RELEASE loServiceUrl
        RELEASE loMonitorHttp
        RELEASE loServiceHost
        RELEASE loTokenFiles
        RELEASE loSharepointToken
        CANCEL
    ENDIF

    IF (loResult.StringOfEquals("status","completed",0) = 1) THEN
        lnCompleted = 1
    ENDIF

    IF (loResult.StringOfEquals("status","failed",0) = 1) THEN
        loReceipt.UpdateString("status","failed")
        loReceipt.UpdateString("errorCode",loResult.StringOf("error.code"))
        lnSuccess = loReceipt.WriteFile(lcReceiptPath)
        IF (lnSuccess <> 1) THEN
            ? "Could not save the failed-operation receipt."
            RELEASE loToken
            RELEASE loHttp
            RELEASE loResp
            RELEASE loResult
            RELEASE loEndpoint
            RELEASE loFac
            RELEASE loReceipt
            RELEASE loBody
            RELEASE loServiceUrl
            RELEASE loMonitorHttp
            RELEASE loServiceHost
            RELEASE loTokenFiles
            RELEASE loSharepointToken
            CANCEL
        ENDIF

        ? "Copy failed: " + loResult.StringOf("error.code")
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loEndpoint
        RELEASE loFac
        RELEASE loReceipt
        RELEASE loBody
        RELEASE loServiceUrl
        RELEASE loMonitorHttp
        RELEASE loServiceHost
        RELEASE loTokenFiles
        RELEASE loSharepointToken
        CANCEL
    ENDIF

ENDIF

IF (lnCompleted = 1) THEN
    loReceipt.UpdateString("status","completed")
    IF (loResult.JsonTypeOf("resourceId") = 1) THEN
        loReceipt.UpdateString("resourceId",loResult.StringOf("resourceId"))
    ENDIF

    lnSuccess = loReceipt.WriteFile(lcReceiptPath)
    IF (lnSuccess <> 1) THEN
        ? "Copy completed but the receipt could not be saved. Reconcile before another copy."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loEndpoint
        RELEASE loFac
        RELEASE loReceipt
        RELEASE loBody
        RELEASE loServiceUrl
        RELEASE loMonitorHttp
        RELEASE loServiceHost
        RELEASE loTokenFiles
        RELEASE loSharepointToken
        CANCEL
    ENDIF

    ? "Copy completed. Destination drive ID: " + lcDestinationDriveId
    ? "New item ID, if returned: " + loReceipt.StringOf("resourceId")
    *  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.
ELSE
    ? "Copy not completed. Status: " + loResult.StringOf("status")
    ? "Percent complete, if returned: " + loResult.StringOf("percentageComplete")
    ? "Retry-After: " + loResp.GetHeaderField("Retry-After")
ENDIF

RELEASE loToken
RELEASE loHttp
RELEASE loResp
RELEASE loResult
RELEASE loEndpoint
RELEASE loFac
RELEASE loReceipt
RELEASE loBody
RELEASE loServiceUrl
RELEASE loMonitorHttp
RELEASE loServiceHost
RELEASE loTokenFiles
RELEASE loSharepointToken