Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy a file using Microsoft Graph C# SDK

I'm trying to copy a file from a drive to another using the C# SDK for Microsoft Graph, but I get an error that I'm not sure how to handle.

This is my code:

public async Task CopyFile(CopyDriveFileCommand c)
{
    var graphClient = CreateDelegatedGraphClient(c.Token);

    var oldDrive = await graphClient
        .Groups[c.OldGroupId]
        .Drive
        .Request()
        .Select("id")
        .GetAsync();

    var parentReference = new ItemReference
    {
        DriveId = oldDrive.Id,
        Id = c.FileToCopyId
    };

    var result = await graphClient
        .Groups[c.NewGroupId]
        .Drive
        .Root
        .ItemWithPath(c.NewPath)
        .Copy("test.png", parentReference)
        .Request()
        .PostAsync();
}

And this is the error I get:

Code: "-1, Microsoft.SharePoint.Client.InvalidClientQueryException"

Message: "The parameter name does not exist in method GetById."

I'm using a hardcoded name now, but I've also tried sending null as name parameter in Copy() and also the same name as the original file. I get the same error if I send the original filename.

If I send null as name parameter, then I get the same error message, but it says

"The parameter parentReference does not exist in method GetById."

Any suggestions is greatly appreciated!

like image 345
Martin Johansson Avatar asked Mar 23 '26 06:03

Martin Johansson


1 Answers

Your parentReference should contain Ids for the destination, not the source:

var parentReference = new ItemReference
{
    DriveId = "Destination Drive Id",
    Id = "Destination Folder Id"
};

You then copy the file by navigating to the source and copying it to the destination:

var result = await graphClient
    .Groups[c.OldGroupId]
    .Drive
    .Items[c.FileToCopyId]
    .Copy("test.png", parentReference)
    .Request()
    .PostAsync();

From the documentation:

Note: The parentReference should include the driveId and id parameters for the target folder.

like image 199
Marc LaFleur Avatar answered Mar 25 '26 20:03

Marc LaFleur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!