简体   繁体   中英

Renaming a google drive file C#

I am trying to rename a google drive file using google drive v3 Apis. here is my code:

public async Task<File> RenameFile(String fileId,
             String newFilename)
        {
            try
            {
                DriveService service = await GetDriveService();
                // First retrieve the file from the API.
                Google.Apis.Drive.v3.Data.File file = service.Files.Get(fileId).Execute();

                // File's new metadata.
                // file.Name = newFilename;
                file.OriginalFilename = newFilename;
                File newFile = new File();
                newFile = file;
                // Send the request to the API.
                FilesResource.UpdateRequest request = service.Files.Update(newFile, fileId);
                request.Fields = "id, name, thumbnailLink";
                File uploadedFile = request.Execute();

                return uploadedFile;
            }
            catch (Exception e)
            {
                Console.WriteLine("An error occurred: " + e.Message);
                return null;
            }

this is throwing an error:

An error occurred: Google.Apis.Requests.RequestError The resource body includes fields which are not directly writable. [403] Errors [ Message[The resource body includes fields which are not directly writable.] Location[ - ] Reason[fieldNotWritable] Domain[global] ]

Please help me with this, I have tried many ways, but its not working.

My drive and files are shared with the single user only, and I am using a console self hosted service to interact with drive, so finally its a single user who is using drive through API.

Your driveService.Files.Get(fileId).Execute() request returns an object with a file.Id which cannot be overwritten. So, set it to null.

        private static void OverwriteDriveFileNames(DriveService driveService)
    {
        string fileId = "myId";
        Google.Apis.Drive.v3.Data.File file = driveService.Files.Get(fileId).Execute();
        file.Id = null;
        FilesResource.UpdateRequest request = driveService.Files.Update(file, fileId);
        request.Execute();
    }

You only rename the files or folders you own. Otherwise you will get message error 403:

An error occurred: Google.Apis.Requests.RequestError The resource body includes fields which are not directly writable. [403] Errors [ Message[The resource body includes fields which are not directly writable.] Location[ - ] Reason[fieldNotWritable] Domain[global] ]

The solution here: You can make a copy or use Credential of owner's user.

Hope this help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM