You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Drive API v3(C#):排除指定ID获取子文件夹列表报错解决

Fixing 400 Error When Excluding Specific Folder IDs in Google Drive API Query

The 400 error you're hitting comes from invalid query syntax in your Google Drive API request. Let me break down the issue and fix it for you:

What's Wrong with the Original Approach?

Your generated query chains multiple and not id='xxx' clauses, like this:

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

While this makes logical sense, the Drive API's query parser rejects this format. The platform expects you to use the not in operator for excluding multiple values in a single clause.

Fixed Implementation

Update the excludeIds handling section in your ListWithoutIds method to use the correct syntax:

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) {
        // Replace multiple "and not id" clauses with a single "not in" statement
        var excludedIdsString = string.Join("','", excludeIds);
        request.Q = $"{request.Q} and not id in ('{excludedIdsString}')";
    }
    return FileListData.From(await request.ExecuteAsync());
}

Resulting Valid Query

With this change, your query will now follow the Drive API's supported syntax:

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

Quick Tips

  • Always use in/not in for filtering multiple values in Drive API queries—this is the officially recommended approach.
  • Drive IDs don't typically contain special characters like quotes, so the string joining here is safe. If you ever need to handle IDs with special characters, you'd need to escape them properly, but that's not necessary for standard Drive resource IDs.

内容的提问来源于stack exchange,提问作者Snake Eyes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 08:02:40