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

如何通过Microsoft Graph高效获取SharePoint的文件夹及子文件夹

高效获取SharePoint所有文件夹及子文件夹的方案

针对你提出的三个方案,以下是具体的可行性分析和实现建议:

A. 更高效的文件夹获取方式

优化列表查询(解决资源超限问题)

之前的列表查询报错源于未索引字段过滤导致的资源消耗过高,可通过以下方式优化:

  1. 使用内容类型ID过滤:文件夹的内容类型ID固定以0x0120开头,该字段为默认索引项,替换原过滤条件为:
    GET https://graph.microsoft.com/v1.0/sites/{site-id}/lists/{list-id}/items?$select=id,fields/FileLeafRef,fields/FileRef&$filter=contentType/id eq '0x0120'
    
    无需携带HonorNonIndexedQueriesWarningMayFailRandomly请求头,可避免资源超限提示。
  2. 精简返回字段:通过$select仅获取必要字段(如文件夹ID、名称、路径),减少数据传输量。

结合Drive API的分页与递归

使用Drive API时,通过分页($top参数最大设为1000)和递归逻辑提升效率:

private async Task<List<DriveItem>> GetAllFoldersAsync(GraphServiceClient graphClient, string driveId, string parentId = "root")
{
    var folders = new List<DriveItem>();
    var request = graphClient.Drives[driveId].Items[parentId].Children
        .Request()
        .Filter("folder ne null")
        .Select("id,name,parentReference")
        .Top(1000);

    do
    {
        var response = await request.GetAsync();
        folders.AddRange(response.CurrentPage);
        request = response.NextPageRequest;
    } while (request != null);

    // 递归获取子文件夹
    foreach (var folder in folders.ToList())
    {
        folders.AddRange(await GetAllFoldersAsync(graphClient, driveId, folder.Id));
    }

    return folders;
}

B. 通过搜索返回文件夹

可行,利用Graph的搜索能力可一次性获取站点内所有文件夹,适合大范围检索:

Drive级搜索

通过Drive的search方法直接筛选文件夹:

var searchResults = await graphClient.Drives["drive-id"].Root
    .Search("is:folder")
    .Request()
    .Select("id,name,parentReference")
    .GetAsync();

站点全局搜索

若需跨文档库搜索,使用全局搜索端点:

POST https://graph.microsoft.com/v1.0/search/query
Content-Type: application/json

{
  "requests": [
    {
      "entityTypes": ["listItem"],
      "query": {
        "queryString": "contenttype:Folder site:{site-id}"
      },
      "select": ["id", "name", "webUrl"]
    }
  ]
}

注意:搜索结果存在15-30分钟延迟,不适合实时获取最新文件夹。

C. 在children端点仅列出文件夹

完全可行,这是优化递归遍历效率的核心手段:
通过$filter=folder ne null直接过滤子项中的文件夹,避免遍历文件:

GET https://graph.microsoft.com/v1.0/drives/{drive-id}/items/{parent-id}/children?$filter=folder ne null&$select=id,name

将该过滤条件整合到递归逻辑中(如A方案的代码示例),可大幅减少请求的数据量和处理时间。


内容的提问来源于stack exchange,提问作者Phil Salomon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 15:25:41