【问题标题】:Renaming a google drive file C#重命名谷歌驱动器文件C#
【发布时间】:2020-01-16 16:49:33
【问题描述】:

我正在尝试使用 google drive v3 API 重命名 google drive 文件。 这是我的代码:

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;
            }

这是抛出一个错误:

发生错误:Google.Apis.Requests.RequestError 资源主体包括不可直接写入的字段。 [403] 错误 [ 消息[资源主体包括不可直接写入的字段。]位置[-]原因[fieldNotWritable]域[全局] ]

请帮帮我,我尝试了很多方法,但都不起作用。

我的驱动器和文件仅与单个用户共享,并且我使用控制台自托管服务与驱动器交互,因此最终它是通过 API 使用驱动器的单个用户。

【问题讨论】:

标签: c# google-drive-api rename


【解决方案1】:

您的 driveService.Files.Get(fileId).Execute() 请求返回一个对象,该对象的 file.Id 不能被覆盖。因此,将其设置为 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();
    }

【讨论】:

    【解决方案2】:

    您只能重命名您拥有的文件或文件夹。否则你会得到消息错误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] ]
    

    这里的解决方案:您可以复制或使用所有者用户的凭据。

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多