microsoft-graph-apionedrivemicrosoft-graph-sdks

How do I replace an existing item(File content) using Graph sdk (.NET C#)?


I'm using MS Graph SDK to replace the existing file.

I find a way to upload new file to onedrive, but I'm still having problem with finding a way to replace the existing file. (assume that I already have driveID and ItemID)

I look through this documents but cannot find replacing file with MS graph sdk. https://learn.microsoft.com/en-us/graph/sdks/large-file-upload?tabs=csharp https://learn.microsoft.com/en-us/onedrive/developer/rest-api/api/driveitem_put_content?view=odsp-graph-online.

Bellow is my code uploading new (small) file to drive and it works well

Microsoft.Kiota.Abstractions.RequestInformation requestInformation = gsc.Drives[myDrive.Id].Root.ItemWithPath(fileFullPath).Content.ToPutRequestInformation(memoryStream);
requestInformation.URI = new Uri(requestInformation.URI.OriginalString + "?@microsoft.graph.conflictBehavior=rename");

var uploadResult = gsc.RequestAdapter.SendAsync<DriveItem>(requestInformation, DriveItem.CreateFromDiscriminatorValue).GetAwaiter().GetResult();

However, I'm looking for replacing existing file so I was thinking I should use something else than 'ItemWithPath(fileFullPath)'.

Just thinking something like this but having syntax error

var uploadSession = await client.Drives[driveId].Items[itemId].CreateUploadSession(uploadSessionRequestBody).PatchAsync();

'you can't use DriveItemItemRequestBuilder.CreateUploadSession' as method'

How can I replace file using graph sdk? Please help


Solution

  • I figure it out! This code is working :)

    Microsoft.Kiota.Abstractions.RequestInformation requestInformationsss = gsc.Drives[driveId].Items[itemId].Content.ToPutRequestInformation(memoryStream);
    requestInformationsss.URI = new Uri(requestInformationsss.URI.OriginalString + "?@microsoft.graph.conflictBehavior=replace");
    
    var uploadResult = gsc.RequestAdapter.SendAsync<DriveItem>(requestInformationsss, DriveItem.CreateFromDiscriminatorValue).GetAwaiter().GetResult();