Home > Blockchain >  Google Drive API: How to update Parents property of File in C#?
Google Drive API: How to update Parents property of File in C#?

Time:05-11

I am attempting to copy a file from one folder to another using the C# google drive API.

Unfortunately, there is no documentation (that I can find) for doing this in C#: https://developers.google.com/drive/api/guides/folder

Here are a few ways I've tried:

Google.Apis.Drive.v3.Data.File file = _files.Where(x => x.Name == fileName).First();

_driveService.Files.Update(file, file.Id).AddParents = _destinationFolderId;

_driveService.Files.Update(file, file.Id).Execute();
Google.Apis.Drive.v3.Data.File file = _files.Where(x => x.Name == fileName).First();

file.Parents = new List<string> { _destinationFolderId  };

_driveService.Files.Update(file, file.Id).Execute();
Google.Apis.Drive.v3.Data.File file = _files.Where(x => x.Name == fileName).First();

_driveService.Files.Update(file, file.Id).Fields = "addParents";

_driveService.Files.Update(file, file.Id).Execute();

However, all of these throw an error:

The service drive has thrown an exception. HttpStatusCode is Forbidden. The parents field is not directly writable in update requests. Use the addParents and removeParents parameters instead.

There are no addParents or removeParents parameters that I can see, like there are in the python API:

file = drive_service.files().update(fileId=file_id,
                                    addParents=folder_id,
                                    removeParents=previous_parents,
                                    fields='id, parents').execute()

Perhaps the error message is misleading / incorrect?

CodePudding user response:

The update method follows the patch methodology. This means that you only send what you want to update and not the other fields.

Updating parents however is a little different it requires the user of the AddParents and RemoveParents methods. If you dont actually want to change any of the other metadata in the file then you can just send a null value for the file body.

var updateRequest = service.Files.Update(null, fileId);
updateRequest.AddParents = folderId;
updateRequest.Execute();
  • Related