3

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!

Community
  • 1
  • 1
Martin Johansson
  • 773
  • 1
  • 11
  • 27

1 Answers1

3

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.

Marc LaFleur
  • 31,987
  • 4
  • 37
  • 63