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

SharePoint中获取子文件夹文件或统计文件数遇列表视图阈值错误

SharePoint统计子文件夹文件数量触发列表视图阈值错误的解决方法

问题描述

尝试统计SharePoint列表中特定子文件夹的文件数量时,触发如下错误:

{"The attempted operation is prohibited because it exceeds the list view threshold."}

原代码:

List list = CContext.Web.Lists.GetByTitle("Lead");
CContext.Load(list);
CContext.Load(list.RootFolder);
CContext.Load(list.RootFolder.Folders);
CContext.Load(list.RootFolder.Files);
CContext.ExecuteQuery();
FolderCollection folderCollection = list.RootFolder.Folders;
List<string> lstFile = new List<string>();
Console.WriteLine("\nCount total sub folder : " + folderCollection.Count);
if (folderCollection.Count > 0)
{
    foreach (Folder folder in folderCollection)
    {
        if (folder.Name == "00111_ACCC74CD7C16VMD11956100224805F1EB")
        {
            CContext.Load(folder.Files);
            CContext.ExecuteQuery();
            FileCollection fileCol = folder.Files;
            if (fileCol.Count > 0)
            {
                foreach (File file in fileCol.ToArray())
                {
                    Console.WriteLine("\nFile Name : " + file.Name);
                }
            }
        }
    }
}

问题原因

错误源于SharePoint的列表视图阈值限制(默认值为5000),当一次性加载的文件夹、文件数量超过该阈值时,系统会禁止操作。原代码先加载根文件夹下所有子文件夹,若根目录下子文件夹数量过多,就会触发这个限制。

优化方案

1. 直接定位目标文件夹,避免加载全部子文件夹

不需要遍历根目录下所有文件夹再筛选,直接通过服务器相对URL获取目标文件夹,减少数据加载量:

// 替换为你的站点实际路径,格式为 "/sites/站点名称/列表名称/目标文件夹名称"
string targetFolderUrl = "/sites/YourSite/Lead/00111_ACCC74CD7C16VMD11956100224805F1EB";
Folder targetFolder = CContext.Web.GetFolderByServerRelativeUrl(targetFolderUrl);

// 加载目标文件夹的文件
CContext.Load(targetFolder.Files);
CContext.ExecuteQuery();

Console.WriteLine($"目标文件夹文件总数:{targetFolder.Files.Count}");
foreach (File file in targetFolder.Files)
{
    Console.WriteLine($"文件名:{file.Name}");
}

2. 分页加载应对大数量文件

如果目标文件夹内文件数量也可能超过阈值,需要用分页方式分批获取:

string targetFolderUrl = "/sites/YourSite/Lead/00111_ACCC74CD7C16VMD11956100224805F1EB";
Folder targetFolder = CContext.Web.GetFolderByServerRelativeUrl(targetFolderUrl);

int skip = 0;
const int pageSize = 5000;
List<File> allFiles = new List<File>();

while (true)
{
    // 分页获取文件
    var filePage = targetFolder.Files.Skip(skip).Take(pageSize);
    CContext.Load(filePage);
    CContext.ExecuteQuery();

    var filesInPage = filePage.ToList();
    if (filesInPage.Count == 0)
        break;

    allFiles.AddRange(filesInPage);
    skip += pageSize;
}

Console.WriteLine($"目标文件夹文件总数:{allFiles.Count}");
foreach (File file in allFiles)
{
    Console.WriteLine($"文件名:{file.Name}");
}

额外建议

  • 确保操作账户拥有目标文件夹的读取权限
  • 对于超大型文档库,建议使用文件夹内容类型或给常用字段添加索引,优化数据查询效率

内容的提问来源于stack exchange,提问作者Vijay Dantani

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 10:30:45