如何使用Google Drive V3 API(C#)恢复回收站文件?
如何通过Google Drive V3 API(C#)恢复回收站中的文件
Google Drive V3 API没有提供专门的Untrash或Restore方法,恢复回收站文件的官方方式是修改文件元数据,将Trashed字段设置为false,同时确保恢复后文件回到原目录(如果有父目录的话)。
核心实现逻辑
- 筛选回收站文件:通过
Files.List接口,用trashed=true的查询条件过滤已删除的文件 - 更新元数据恢复文件:构造仅包含
Trashed = false的元数据对象,调用Files.Update接口完成恢复 - 保留原目录关联:如果文件原本有父目录,通过
AddParents参数传入原父目录ID,避免文件恢复后跑到根目录
完整可运行代码
public void Restore(DateTime from, DateTime to) { var driveService = DriveServiceFactory.Create(); foreach (var file in GetTrashedFiles(driveService, from, to)) { // 仅构造需要更新的元数据字段(API支持部分更新,无需传全量属性) var updateMetadata = new Google.Apis.Drive.v3.Data.File { Trashed = false }; var updateRequest = driveService.Files.Update(updateMetadata, file.Id); // 若文件有原父目录,恢复时关联回去,避免文件出现在根目录 if (file.Parents != null && file.Parents.Any()) { updateRequest.AddParents = string.Join(",", file.Parents); } updateRequest.Execute(); } } public static class DriveServiceFactory { public static DriveService Create() { UserCredential credential; using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read)) { string credPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), ".credentials/drive-dotnet-quickstart.json"); credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, new[] { DriveService.Scope.Drive, DriveService.Scope.DriveFile, DriveService.Scope.DriveMetadata }, "user", CancellationToken.None, new FileDataStore(credPath, true) ).Result; Console.WriteLine("Credential file saved to: " + credPath); } return new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "MyApp", }); } } private IEnumerable<Google.Apis.Drive.v3.Data.File> GetTrashedFiles(DriveService driveService, DateTime @from, DateTime to) { var fileFields = "id, name, parents, trashed, modifiedTime"; var listRequest = driveService.Files.List(); listRequest.PageSize = 1000; listRequest.Fields = $"nextPageToken, files({fileFields})"; // 直接在查询条件中加入时间过滤,减少内存处理压力 listRequest.Q = $"trashed=true and modifiedTime >= '{from:yyyy-MM-ddTHH:mm:ssZ}' and modifiedTime <= '{to:yyyy-MM-ddTHH:mm:ssZ}'"; do { var filesFeed = listRequest.Execute(); if (filesFeed.Files == null) break; foreach (var file in filesFeed.Files) { yield return file; } listRequest.PageToken = filesFeed.NextPageToken; } while (!string.IsNullOrEmpty(listRequest.PageToken)); }
关键细节说明
- 部分更新优化:构造元数据时只设置需要修改的
Trashed字段,API会自动保留其他原有属性,提升请求效率 - 目录关联:如果忽略
AddParents,恢复后的文件会直接出现在Google Drive根目录,必须传入原父目录ID才能回到原位置 - 权限要求:确保申请的OAuth2.0权限包含
Drive或DriveFile,否则会因权限不足无法修改文件状态 - 分页处理:回收站文件数量可能较多,代码通过
NextPageToken处理分页,确保遍历所有符合条件的文件
内容的提问来源于stack exchange,提问作者theateist
相关产品推荐
相关产品推荐

