如何用C#从SharePoint文件夹获取文件名及大小并导出至Excel?求实现方案
当然可以!我来给你分享两种实用的实现方案,分别是SharePoint CSOM(客户端对象模型)和Microsoft Graph API,这俩都是目前C#操作SharePoint的主流方式,最后再把收集到的文件信息导出到Excel里。
准备工作
先安装必要的NuGet包:
- 若使用CSOM:安装
Microsoft.SharePointOnline.CSOM(针对SharePoint Online,本地服务器对应版本的CSOM包) - 若使用Graph API:安装
Microsoft.Graph和Microsoft.Graph.Auth - Excel导出:推荐用
EPPlus(轻量级且功能全,注意EPPlus 5+需要商业许可证,非商业场景可选用4.x版本)
这种方式对SharePoint Online和本地服务器都兼容,代码逻辑直接易懂:
using Microsoft.SharePoint.Client; using OfficeOpenXml; using System; using System.Collections.Generic; using System.IO; using System.Security; class SharePointFileExporter { static void Main(string[] args) { // 配置参数 string siteUrl = "https://yourtenant.sharepoint.com/sites/YourSite"; string folderRelativeUrl = "/sites/YourSite/Shared Documents/TargetFolder"; string excelFilePath = @"C:\Export\SharePointFiles.xlsx"; string username = "your@tenant.onmicrosoft.com"; string password = "YourPassword"; // 初始化客户端上下文 using (ClientContext context = new ClientContext(siteUrl)) { // 设置认证(SharePoint Online用用户名密码,本地服务器可换默认凭据) SecureString securePassword = new SecureString(); foreach (char c in password) securePassword.AppendChar(c); context.Credentials = new SharePointOnlineCredentials(username, securePassword); try { // 获取目标文件夹及文件信息 Folder targetFolder = context.Web.GetFolderByServerRelativeUrl(folderRelativeUrl); context.Load(targetFolder.Files, files => files.Include( file => file.Name, file => file.Length )); context.ExecuteQuery(); // 收集文件数据 List<FileInfoModel> fileInfos = new List<FileInfoModel>(); foreach (Microsoft.SharePoint.Client.File file in targetFolder.Files) { fileInfos.Add(new FileInfoModel { FileName = file.Name, FileSizeInKB = Math.Round(file.Length / 1024.0, 2) }); } // 导出到Excel ExportToExcel(fileInfos, excelFilePath); Console.WriteLine("文件信息已成功导出到Excel!"); } catch (Exception ex) { Console.WriteLine($"出错了:{ex.Message}"); } } } // Excel导出方法 private static void ExportToExcel(List<FileInfoModel> fileInfos, string filePath) { Directory.CreateDirectory(Path.GetDirectoryName(filePath)); using (ExcelPackage package = new ExcelPackage()) { ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("文件列表"); // 设置表头 worksheet.Cells[1, 1].Value = "文件名"; worksheet.Cells[1, 2].Value = "文件大小(KB)"; // 填充数据 int row = 2; foreach (var info in fileInfos) { worksheet.Cells[row, 1].Value = info.FileName; worksheet.Cells[row, 2].Value = info.FileSizeInKB; row++; } // 自动调整列宽 worksheet.Cells.AutoFitColumns(); package.SaveAs(new FileInfo(filePath)); } } } // 文件信息模型类 public class FileInfoModel { public string FileName { get; set; } public double FileSizeInKB { get; set; } }
注意:如果是SharePoint本地服务器,把认证部分替换为
context.Credentials = System.Net.CredentialCache.DefaultCredentials;即可。
方案二:Microsoft Graph API实现(推荐云原生场景)
Graph API是微软统一的云服务API,不仅能操作SharePoint,还能对接OneDrive、Outlook等,适合现代云环境:
using Microsoft.Graph; using Microsoft.Graph.Auth; using Microsoft.Identity.Client; using OfficeOpenXml; using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; class GraphSharePointExporter { // Azure AD应用注册信息(需提前在Azure AD注册应用并授予权限) private static readonly string ClientId = "YourAppClientId"; private static readonly string TenantId = "YourTenantId"; private static readonly string ClientSecret = "YourAppClientSecret"; static async Task Main(string[] args) { // 配置参数 string siteId = "YourSiteId"; // 可从SharePoint站点URL获取或通过Graph API查询 string driveId = "YourDriveId"; // 站点默认文档库ID string folderId = "TargetFolderId"; // 目标文件夹ID string excelFilePath = @"C:\Export\GraphSharePointFiles.xlsx"; try { // 初始化Graph客户端 IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder .Create(ClientId) .WithTenantId(TenantId) .WithClientSecret(ClientSecret) .Build(); ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication); GraphServiceClient graphClient = new GraphServiceClient(authProvider); // 获取文件夹下的文件(仅请求需要的字段,提升性能) var files = await graphClient.Sites[siteId].Drives[driveId].Items[folderId].Children .Request() .Select("name,size") .GetAsync(); // 收集文件数据 List<FileInfoModel> fileInfos = new List<FileInfoModel>(); foreach (var item in files) { if (item.File != null) // 仅处理文件,排除文件夹 { fileInfos.Add(new FileInfoModel { FileName = item.Name, FileSizeInKB = Math.Round(item.Size.Value / 1024.0, 2) }); } } // 导出到Excel ExportToExcel(fileInfos, excelFilePath); Console.WriteLine("文件信息已成功导出到Excel!"); } catch (Exception ex) { Console.WriteLine($"出错了:{ex.Message}"); } } // 复用Excel导出方法 private static void ExportToExcel(List<FileInfoModel> fileInfos, string filePath) { Directory.CreateDirectory(Path.GetDirectoryName(filePath)); using (ExcelPackage package = new ExcelPackage()) { ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("文件列表"); worksheet.Cells[1, 1].Value = "文件名"; worksheet.Cells[1, 2].Value = "文件大小(KB)"; int row = 2; foreach (var info in fileInfos) { worksheet.Cells[row, 1].Value = info.FileName; worksheet.Cells[row, 2].Value = info.FileSizeInKB; row++; } worksheet.Cells.AutoFitColumns(); package.SaveAs(new FileInfo(filePath)); } } } public class FileInfoModel { public string FileName { get; set; } public double FileSizeInKB { get; set; } }
最佳实践建议
- API选择:如果是云原生架构,优先用Graph API;如果是传统SharePoint本地服务器或需兼容旧版本,CSOM更合适。
- 权限最小化:给账号/应用分配最小必要权限,比如CSOM用只读权限,Graph API用
Sites.Read.All而非读写权限。 - 错误处理:实际项目中要增加网络异常、权限不足、文件夹不存在等场景的针对性处理。
- 性能优化:文件数量多时,用分页查询(CSOM的
ListItemCollectionPosition、Graph API的@odata.nextLink)避免内存溢出。 - Excel导出:非商业场景用EPPlus 4.x免费版,商业项目可考虑ClosedXML或购买EPPlus商业许可证。
内容的提问来源于stack exchange,提问作者magesh
相关产品推荐
相关产品推荐

