'Copy a file, rename in case it exists using MS Graph for Onedrive/Sharepoint

I am copying a file from one drive to another. As part of the body request, I am also providing conflictBehavior as rename (tried with replace as well) but the copy is failing.

POST: https://graph.microsoft.com/beta/users/{user-id}/drive/items/{item-id}/copy
Body:
{
    "parentReference": {"id": {folder-id-to-copy}, "driveId": {drive-id},
    "@microsoft.graph.conflictBehavior": "rename"
}

After executing above command, as expected I get a 202 and in the header I look at Location. When querying the monitor URL, I see the below error:

{
    "@odata.context": "https://{host-name}/_api/v2.1/$metadata#drives('default')/operations/$entity",
    "id": "7a0decd4-df2f-4717-8eee-b7c2cd131009",
    "createdDateTime": "0001-01-01T00:00:00Z",
    "lastActionDateTime": "0001-01-01T00:00:00Z",
    "status": "failed",
    "error": {
        "code": "nameAlreadyExists",
        "message": "Name already exists"
    }
}

What to pass in order to rename/replace existing file while copying



Solution 1:[1]

If you are trying to rename it with special name, then try this.

POST /users/{user-id}/drive/items/{item-id}/copy
Content-Type: application/json

{
  "parentReference": {
    "id": {folder-id-to-copy}, "driveId": {drive-id},
  },
  "name": "your_file_name (copy).txt"
}

Reference here: https://docs.microsoft.com/en-us/graph/api/driveitem-copy?...

And if you want to rename the file automatically, then try this using Instance Attributes.

POST /users/{user-id}/drive/items/{item-id}/[email protected]=rename
Content-Type: application/json

{
  "name": "{filename}"
}

name should be provided.

Solution 2:[2]

if you are using GraphServiceClient, you can do the following:

GraphServiceClient graphClient = new GraphServiceClient( authProvider );

var parentReference = new ItemReference
{
    DriveId = "6F7D00BF-FC4D-4E62-9769-6AEA81F3A21B",
    Id = "DCD0D3AD-8989-4F23-A5A2-2C086050513F"
};
// To resolve the issue: Code: nameAlreadyExists Message: The specified item name already exists. Copy
List<QueryOption> options = new List<QueryOption>
{
    new QueryOption("@microsoft.graph.conflictBehavior", "rename")
};
var name = "contoso plan (copy).txt";

await graphClient.Me.Drive.Items["{driveItem-id}"]
    .Copy(name,parentReference)
    .Request(options)
    .PostAsync();

Ref https://docs.microsoft.com/en-us/graph/api/driveitem-copy?view=graph-rest-1.0&tabs=csharp

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Ken Nguyen