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

如何用Graph API高效查找OneDrive特定扩展名文件(C#/.NET Core)

优化OneDrive特定扩展名文件查找的方法

核心思路:用Graph API原生过滤替代递归遍历

递归遍历文件夹的性能瓶颈在于多次API调用,我们可以直接通过Graph API的属性过滤或搜索能力,一次性获取所有子文件夹中符合扩展名要求的文件,无需手动递归。

问题根源说明

你之前尝试的endswith(name, '.docx')报错,是因为Graph API对name字段的endswith操作支持有限;SearchWithQ报错则大概率是语法或权限问题。正确的做法是直接针对file/extension属性过滤——该属性专门存储不带前置点的文件扩展名(如docx),支持稳定的相等匹配。


C# 代码示例:基于属性过滤批量获取文件

using Microsoft.Graph;
using Microsoft.Graph.Models;
using System.Collections.Generic;
using System.Threading.Tasks;

public async Task<List<DriveItem>> GetAllDocxFilesAsync(GraphServiceClient client, string driveId)
{
    var docxFiles = new List<DriveItem>();
    string nextPageLink = null;

    do
    {
        var request = client.Drives[driveId].Items["root"]
            .Children
            .Request()
            .Filter("file ne null and file/extension eq 'docx'") // 过滤文件且扩展名为docx
            .Top(100) // 分页大小,可根据需求调整
            .Select("id, name, webUrl, file"); // 只请求需要的属性,减少数据传输

        // 处理分页
        if (!string.IsNullOrEmpty(nextPageLink))
        {
            request = client.Drives[driveId].Items["root"]
                .Children
                .Request(nextPageLink);
        }

        var result = await request.GetAsync();
        docxFiles.AddRange(result.CurrentPage);
        nextPageLink = result.NextPageRequest?.NextPageLink;

    } while (!string.IsNullOrEmpty(nextPageLink));

    return docxFiles;
}

C# 代码示例:用Search API灵活查找

如果需要结合文件名关键词+扩展名的搜索,可使用Graph的Search API,正确调用方式如下:

public async Task<List<DriveItem>> SearchDocxFilesAsync(GraphServiceClient client, string driveId)
{
    var docxFiles = new List<DriveItem>();
    string nextPageLink = null;

    do
    {
        var request = client.Drives[driveId].Items["root"]
            .Search(q: "*.docx") // 通配符匹配所有docx文件
            .Request()
            .Top(100)
            .Select("id, name, webUrl, file");

        // 处理分页
        if (!string.IsNullOrEmpty(nextPageLink))
        {
            request = client.Drives[driveId].Items["root"]
                .Search(q: "*.docx")
                .Request(nextPageLink);
        }

        var result = await request.GetAsync();
        docxFiles.AddRange(result.CurrentPage);
        nextPageLink = result.NextPageRequest?.NextPageLink;

    } while (!string.IsNullOrEmpty(nextPageLink));

    return docxFiles;
}

关键注意事项

  • 权限要求:确保应用已获得Files.Read.All(或针对特定用户的Files.Read)权限,否则会出现访问拒绝或无结果的情况。
  • 分页处理:Graph API默认返回结果数量有限,必须通过NextPageLink处理分页才能获取全部匹配文件。
  • 属性精简:用Select只请求必要属性,减少网络传输数据量,进一步提升查询速度。

内容的提问来源于stack exchange,提问作者Chris Fellows

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 17:55:16