列出 id 不是 Google Drive API v3 和 C# 中特定值的目录中的文件夹

List folders from a directory which id is not a specific value in Google Drive API v3 and C#

我想从文件夹 ID 中获取 sub-folders 的列表,但特定 ID(不是全部)除外。我的意思是我想获取 children 哪个 ID 不在我提供的列表中

 public async Task<FileListData> ListWithoutIds(string id, int itemsPerPage = 10, string nextPageToken = null, bool onlyFolders = false, bool onlyFiles = false, string[] excludeIds = null)
{
  if (string.IsNullOrWhiteSpace(id))
  {
    throw new ArgumentException($"'{nameof(id)}' cannot be null or whitespace", nameof(id));
  }

  var request = PrepareListRequest(itemsPerPage, nextPageToken);
  request.Q = $"'{id}' in parents";
  if (onlyFolders)
  {
    request.Q = $"{request.Q} and mimeType='application/vnd.google-apps.folder'";
  }
  else if (onlyFiles)
  {
    request.Q = $"{request.Q} and not mimeType='application/vnd.google-apps.folder'";
  }

  if (excludeIds?.Length > 0)
  {
    request.Q = $"{request.Q} {string.Join(" ", excludeIds.Select(e => $"and not id='{e}'"))}";
  }

  return FileListData.From(await request.ExecuteAsync()); // here I got 400 error
}

private FilesResource.ListRequest PrepareListRequest(int itemsPerPage, string nextPageToken, string[] specificFields = null)
{
  var request = driveService.Files.List();
  request.PageSize = itemsPerPage;
  request.SupportsAllDrives = true;
  request.IncludeItemsFromAllDrives = true;

  if (!string.IsNullOrWhiteSpace(nextPageToken))
  {
    request.PageToken = nextPageToken;
  }

  if (specificFields?.Length > 0)
  {
    var fields = $"{string.Join(",", specificFields)}";
    request.Fields = $"nextPageToken, files({fields.Trim(',')})";
  }
  else
  {
    request.Fields = "nextPageToken, files";
  }
  return request;
}

执行的查询如下所示:

'parentFolderId' in parents and mimeType='application/vnd.google-apps.folder' and not id='Child1Id' and not id='Child2Id' and not id='Child3Id'

我遇到了 400 错误。

如何实现?

Drive API 的查询功能非常有限,列表结果的 id 不是可能的 query term

您需要重构代码的逻辑。

  • 首先使用查询 'parentFolderId' in parents and mimeType='application/vnd.google-apps.folder' 获取您的文件夹列表,然后将 Fields 设置为 files/id
  • 随后以编程方式实现一个过滤器,以从总 ID 列表中减去您要排除的 ID。