Google Drive API按文件名搜索仅返回Chrome近期打开文件问题
Google Drive API 文件名搜索接口仅返回近期浏览器打开过的文件问题
功能实现代码
我编写了一个可按文件名搜索并下载对应Google Drive文件的方法,实现代码如下:
public static void DownloadFile(string filename) { service = GetDriveService(); // 校验文件是否存在并获取文件ID FilesResource.ListRequest listRequest = service.Files.List(); listRequest.SupportsAllDrives = true; listRequest.IncludeItemsFromAllDrives = true; listRequest.PageSize = 1000; listRequest.Q = "name = '" + filename + ".pdf'"; FileList files = listRequest.Execute(); if (files.Files.Count > 0) // 文件存在时执行下载 { var request = service.Files.Get(files.Files[0].Id); var stream = new System.IO.MemoryStream(); request.Download(stream); } }
问题现象
执行FileList files = listRequest.Execute();查询文件列表时,除非我近期在Chrome浏览器的Google Drive中打开过目标文件,否则接口返回的文件数始终为0,表现类似文件未被索引,我怀疑是否遗漏了必要的请求参数。
已完成的测试验证:
- 对大量文件进行测试,结果完全一致:若目标文件曾在Chrome端近期打开,
FileList files = listRequest.Execute();会返回1条对应文件记录,否则无任何返回结果 - 测试了仅搜索特定文件夹的场景,问题仍然存在
补充配置信息
GetDriveService鉴权方法的实现代码如下:
private static DriveService GetDriveService() { string[] scopes = new string[] { DriveService.Scope.Drive }; // 全量访问权限 GoogleDrive cr = JsonConvert.DeserializeObject<GoogleDrive>(System.IO.File.ReadAllText(@"\\PATH_TO_JSONFILE\GoogleAPI.json")); ServiceAccountCredential xCred = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(cr.client_email) { User = "xxxxx@xxxx.xx", Scopes = new[] { DriveService.Scope.Drive } }.FromPrivateKey(cr.private_key)); DriveService service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = xCred, ApplicationName = "APPLICATION_NAME", }); return service; }
上述代码中
User字段配置的邮箱账号,与我在Chrome端打开文件使用的Google账号完全一致。
内容的提问来源于stack exchange,提问作者Jeanfabre
相关产品推荐
相关产品推荐

