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

SharePoint本地API及CSOM获取指定文件夹文件列表失败问题排查

问题分析与解决建议

一、CSOM代码问题(folder变量为空)

folder为空的核心原因大概率是服务器相对路径格式错误:

  • GetFolderByServerRelativeUrl要求传入从Web应用根目录开始的完整相对路径,而非仅网站内部的相对路径。例如:
    若你的网站集地址是http://sp-server/sites/team-site,文件夹实际路径是该网站下的MyRoom/Document/MyFolder,则正确路径应为"/sites/team-site/MyRoom/Document/MyFolder",而非仅"MyRoom/Document/MyFolder"。
  • 修正后的CSOM代码:
Function ListFilesInFolder(in_Context As ClientContext, in_SharePointFolderAndRoom As String) As List(Of String)
    Dim out_List As List(Of String) = New List(Of String)

    Try
        Dim web As Web = in_Context.Web
        ' 自动补全完整服务器相对路径,避免格式错误
        Dim fullServerRelativeUrl As String = If(in_SharePointFolderAndRoom.StartsWith("/"), 
            in_SharePointFolderAndRoom, 
            $"{web.ServerRelativeUrl}/{in_SharePointFolderAndRoom}").Replace("//", "/")
        
        Dim folder As Folder = web.GetFolderByServerRelativeUrl(fullServerRelativeUrl)
        ' 显式指定要加载的文件属性,避免默认元数据缺失
        in_Context.Load(folder.Files, Function(files) files.Include(Function(f) f.Name))
        in_Context.ExecuteQuery()

        For Each file As File In folder.Files
            out_List.Add(file.Name)
        Next

    Catch ex As Exception
        Throw New Exception("Error when listing files: " + ex.Message)
    End Try

    Return out_List
End Function

二、REST API请求问题(ItemCount为3但无文件信息)

  1. 明确指定返回字段/展开资源
    SharePoint REST默认返回精简元数据,不会自动包含文件的详细信息,需通过参数强制获取:
    • 直接请求文件列表时,指定要返回的属性:
      /_api/web/GetFolderByServerRelativeUrl('/sites/team-site/MyRoom/Document/MyFolder')/Files?$select=Name,ServerRelativeUrl
      
    • 请求文件夹端点时,需展开Files关联资源:
      /_api/web/GetFolderByServerRelativeUrl('/sites/team-site/MyRoom/Document/MyFolder')?$expand=Files&$select=Files/Name,ItemCount
      
  2. 检查请求头设置
    确保HttpClient的Accept头设置为application/json;odata=verbose或application/xml;odata=verbose,强制返回完整元数据格式。

三、可能的SharePoint设置限制

  1. 权限验证
    即使能上传下载文件,仍需确认当前用户是否拥有查看项目权限(默认包含在读取权限级别中),部分自定义权限可能限制文件列表读取。
  2. 过滤隐藏文件
    若文件是系统隐藏文件(如版本历史文件),默认不会被返回,可通过REST参数过滤普通文件:
    /_api/web/GetFolderByServerRelativeUrl(...)Files?$select=Name&$filter=FileSystemObjectType eq 0
    

内容的提问来源于stack exchange,提问作者Robert Persson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 15:06:15