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

Viewed 246

I want to get list of sub-folders from folder id but except by specific ids (not all of them). I meant I want to get children which id is not in the list I provide

 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
}

and

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

The query executed looks like:

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

And I got 400 error.

How to achive that ?

1 Answers

The query funcitonality of the Drive API is quite limited, the id of the list results is not a possible query term.

You need to reconstruct the logic of your code.

  • First get a list of your folders with the query 'parentFolderId' in parents and mimeType='application/vnd.google-apps.folder' and set Fields to files/id
  • Subsequently implement programmatically a filter to substract from the total id list the ids you want to exclude.
Related