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.
Chilkat Xojo Plugin Downloads
Dim success As Boolean
success = False
// Assumes Chilkat is unlocked. See Global Unlock Sample.
success = False
// Obtain a delegated Graph token with this example's file permissions.
// See OneDrive OAuth2 with PKCE.
Dim token As New Chilkat.JsonObject
token.Strict = True
success = token.LoadFile("qa_data/tokens/oneDrive.json")
If (success <> True) Then
System.DebugLog("Could not load the private OneDrive token cache.")
Return
End If
If ((token.JsonTypeOf("access_token") <> 1) Or (token.StringOfEquals("access_token","",True) = True)) Then
System.DebugLog("Expected a nonempty access_token in the JSON.")
Return
End If
Dim http As New Chilkat.Http
http.AuthToken = token.StringOf("access_token")
http.RequireSslCertVerify = True
http.FollowRedirects = False
http.ConnectTimeout = 20
http.ReadTimeout = 120
http.SetRequestHeader "Accept","application/json"
Dim resp As New Chilkat.HttpResponse
Dim result As New Chilkat.JsonObject
result.Strict = True
Dim driveId As String
driveId = "YOUR_DRIVE_ID"
Dim itemId As String
itemId = "YOUR_ITEM_ID"
Dim endpoint As New Chilkat.StringBuilder
success = endpoint.Append("https://graph.microsoft.com/v1.0/drives/")
success = endpoint.Append(http.UrlEncode(driveId))
success = endpoint.Append("/items/")
success = endpoint.Append(http.UrlEncode(itemId))
Dim destinationDriveId As String
destinationDriveId = "YOUR_DESTINATION_DRIVE_ID"
Dim destinationFolderId As String
destinationFolderId = "YOUR_DESTINATION_FOLDER_ID"
Dim newName As String
newName = "copied-file.txt"
// Use a separate private receipt for each copy operation and account.
Dim accountKey As String
accountKey = "YOUR_LOCAL_ACCOUNT_KEY"
Dim receiptPath As String
receiptPath = "qa_data/oneDrive/copy-receipt.json"
Dim fac As New Chilkat.FileAccess
success = fac.DirEnsureExists("qa_data/oneDrive")
If (success <> True) Then
System.DebugLog("Could not create the private receipt directory.")
Return
End If
Dim receipt As New Chilkat.JsonObject
receipt.Strict = True
If (fac.FileExists(receiptPath) = True) Then
success = receipt.LoadFile(receiptPath)
If (success <> True) Then
System.DebugLog("Invalid receipt; reconcile the existing operation before starting another.")
Return
End If
If (receipt.StringOfEquals("accountKey",accountKey,True) <> True) Then
System.DebugLog("Receipt belongs to another copy operation; no request sent.")
Return
End If
If (receipt.StringOfEquals("sourceDriveId",driveId,True) <> True) Then
System.DebugLog("Receipt belongs to another copy operation; no request sent.")
Return
End If
If (receipt.StringOfEquals("sourceItemId",itemId,True) <> True) Then
System.DebugLog("Receipt belongs to another copy operation; no request sent.")
Return
End If
If (receipt.StringOfEquals("destinationDriveId",destinationDriveId,True) <> True) Then
System.DebugLog("Receipt belongs to another copy operation; no request sent.")
Return
End If
If (receipt.StringOfEquals("destinationFolderId",destinationFolderId,True) <> True) Then
System.DebugLog("Receipt belongs to another copy operation; no request sent.")
Return
End If
If (receipt.StringOfEquals("name",newName,True) <> True) Then
System.DebugLog("Receipt belongs to another copy operation; no request sent.")
Return
End If
If (receipt.StringOfEquals("status","completed",True) = True) Then
System.DebugLog("This copy already completed. Item ID: " + receipt.StringOf("resourceId"))
Return
End If
If (receipt.StringOfEquals("status","failed",True) = True) Then
System.DebugLog("The saved copy failed. Review its error and destination before starting another operation.")
Return
End If
If (receipt.StringOfEquals("status","monitoring",True) <> True) Then
System.DebugLog("Copy outcome is uncertain; reconcile the destination before replacing this receipt.")
Return
End If
If ((receipt.JsonTypeOf("monitorUrl") <> 1) Or (receipt.StringOfEquals("monitorUrl","",True) = True)) Then
System.DebugLog("Expected a nonempty monitorUrl in the JSON.")
Return
End If
Else
success = receipt.UpdateString("accountKey",accountKey)
success = receipt.UpdateString("sourceDriveId",driveId)
success = receipt.UpdateString("sourceItemId",itemId)
success = receipt.UpdateString("destinationDriveId",destinationDriveId)
success = receipt.UpdateString("destinationFolderId",destinationFolderId)
success = receipt.UpdateString("name",newName)
// Save intent before POST so a lost response cannot cause an automatic duplicate copy.
success = receipt.UpdateString("status","pending")
success = receipt.WriteFile(receiptPath)
If (success <> True) Then
System.DebugLog("Could not save the copy intent; nothing submitted.")
Return
End If
Dim body As New Chilkat.JsonObject
success = body.UpdateString("parentReference.driveId",destinationDriveId)
success = body.UpdateString("parentReference.id",destinationFolderId)
success = body.UpdateString("name",newName)
success = endpoint.Append("/copy")
// Omit conflictBehavior: the default is fail, and the query option is not supported by personal OneDrive.
success = http.HttpJson("POST",endpoint.GetAsString(),body,"application/json",resp)
If ((success <> True) And (resp.StatusCode = 0)) Then
System.DebugLog("No HTTP response received; inspect diagnostics privately and reconcile writes before retrying.")
Return
End If
If ((resp.StatusCode <> 202)) Then
System.DebugLog("Unexpected HTTP status: " + Str(resp.StatusCode))
System.DebugLog("Request ID: " + resp.GetHeaderField("request-id"))
If (resp.StatusCode = 429) Then
System.DebugLog("Retry-After: " + resp.GetHeaderField("Retry-After"))
End If
Return
End If
Dim monitorUrl As String
monitorUrl = resp.GetHeaderField("Location")
If (monitorUrl = "") Then
System.DebugLog("Accepted without a monitor URL; keep the pending receipt and reconcile the destination.")
Return
End If
success = receipt.UpdateString("monitorUrl",monitorUrl)
success = receipt.UpdateString("status","monitoring")
success = receipt.WriteFile(receiptPath)
If (success <> True) Then
System.DebugLog("Accepted, but receipt save failed. Do not repeat POST; reconcile the destination.")
Return
End If
System.DebugLog("Copy accepted. Run again later to check its status; honor Retry-After.")
System.DebugLog("Retry-After: " + resp.GetHeaderField("Retry-After"))
Return
End If
// One status request per run. The caller schedules the next run with backoff and Retry-After.
Dim statusUrl As String
statusUrl = receipt.StringOf("monitorUrl")
Dim serviceUrl As New Chilkat.Url
success = serviceUrl.ParseUrl(statusUrl)
If (success <> True) Then
System.DebugLog("Invalid service URL.")
Return
End If
If ((serviceUrl.Ssl <> True) Or (serviceUrl.Host = "") Or (serviceUrl.Login <> "") Or (serviceUrl.Password <> "")) Then
System.DebugLog("Expected an HTTPS service URL without embedded login credentials.")
Return
End If
Dim monitorHttp As New Chilkat.Http
monitorHttp.RequireSslCertVerify = True
monitorHttp.FollowRedirects = False
monitorHttp.ConnectTimeout = 20
monitorHttp.ReadTimeout = 120
Dim serviceHost As New Chilkat.StringBuilder
success = serviceHost.Append(serviceUrl.Host)
If ((serviceHost.ContentsEqual("graph.microsoft.com",False) = True) And (serviceUrl.Port = 443)) Then
monitorHttp.AuthToken = token.StringOf("access_token")
Else
Dim tokenFiles As New Chilkat.FileAccess
If (tokenFiles.FileExists("qa_data/tokens/oneDrive-sharepoint.json") = True) Then
Dim sharepointToken As New Chilkat.JsonObject
sharepointToken.Strict = True
success = sharepointToken.LoadFile("qa_data/tokens/oneDrive-sharepoint.json")
If (success <> True) Then
System.DebugLog("Could not read the private SharePoint token cache.")
Return
End If
If ((sharepointToken.JsonTypeOf("host") <> 1) Or (sharepointToken.StringOfEquals("host","",True) = True)) Then
System.DebugLog("Expected a nonempty host in the JSON.")
Return
End If
If ((sharepointToken.JsonTypeOf("access_token") <> 1) Or (sharepointToken.StringOfEquals("access_token","",True) = True)) Then
System.DebugLog("Expected a nonempty access_token in the JSON.")
Return
End If
// host is a configured exact hostname, not a URL and not obtained from the service response.
If ((serviceHost.ContentsEqual(sharepointToken.StringOf("host"),False) = True) And (serviceUrl.Port = 443)) Then
monitorHttp.AuthToken = sharepointToken.StringOf("access_token")
End If
End If
End If
// With no matching token configured, only a still-valid preauthenticated URL can succeed.
success = monitorHttp.HttpNoBody("GET",statusUrl,resp)
If ((success <> True) And (resp.StatusCode = 0)) Then
System.DebugLog("No HTTP response received; inspect diagnostics privately and reconcile writes before retrying.")
Return
End If
If ((resp.StatusCode <> 200) And (resp.StatusCode <> 202) And (resp.StatusCode <> 303)) Then
System.DebugLog("Unexpected HTTP status: " + Str(resp.StatusCode))
System.DebugLog("Request ID: " + resp.GetHeaderField("request-id"))
If (resp.StatusCode = 429) Then
System.DebugLog("Retry-After: " + resp.GetHeaderField("Retry-After"))
End If
Return
End If
Dim completed As Boolean
completed = resp.StatusCode = 303
If (resp.BodyStr <> "") Then
success = result.Load(resp.BodyStr)
If (success <> True) Then
System.DebugLog("Invalid monitor JSON; keep the receipt and inspect the operation.")
Return
End If
If (result.StringOfEquals("status","completed",False) = True) Then
completed = True
End If
If (result.StringOfEquals("status","failed",False) = True) Then
success = receipt.UpdateString("status","failed")
success = receipt.UpdateString("errorCode",result.StringOf("error.code"))
success = receipt.WriteFile(receiptPath)
If (success <> True) Then
System.DebugLog("Could not save the failed-operation receipt.")
Return
End If
System.DebugLog("Copy failed: " + result.StringOf("error.code"))
Return
End If
End If
If (completed = True) Then
success = receipt.UpdateString("status","completed")
If (result.JsonTypeOf("resourceId") = 1) Then
success = receipt.UpdateString("resourceId",result.StringOf("resourceId"))
End If
success = receipt.WriteFile(receiptPath)
If (success <> True) Then
System.DebugLog("Copy completed but the receipt could not be saved. Reconcile before another copy.")
Return
End If
System.DebugLog("Copy completed. Destination drive ID: " + destinationDriveId)
System.DebugLog("New item ID, if returned: " + receipt.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
System.DebugLog("Copy not completed. Status: " + result.StringOf("status"))
System.DebugLog("Percent complete, if returned: " + result.StringOf("percentageComplete"))
System.DebugLog("Retry-After: " + resp.GetHeaderField("Retry-After"))
End If