如何使用Microsoft Graph API C# SDK上传文件到SharePoint库文件夹
前置依赖
首先安装所需NuGet包:
Microsoft.Graph:Graph SDK核心包Azure.Identity:用于身份认证
场景1:小文件(≤4MB)直接上传
using Microsoft.Graph; using Azure.Identity; using System.IO; // 1. 初始化Graph客户端,示例使用客户端凭据流,可替换为实际使用的授权流 var scopes = new[] { "https://graph.microsoft.com/.default" }; var tenantId = "你的Azure AD租户ID"; var clientId = "你的应用注册客户端ID"; var clientSecret = "你的应用注册客户端密钥"; var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret); var graphClient = new GraphServiceClient(clientSecretCredential, scopes); // 2. 配置上传参数 string siteHost = "你的租户.sharepoint.com"; string siteRelativePath = "sites/你的站点名"; string libraryName = "目标文档库名称"; string targetSubfolderPath = "部门文档/市场部/2024活动"; // 子文件夹相对于库根的路径 string uploadFileName = "活动策划方案.docx"; string localFilePath = @"C:\本地存储路径\活动策划方案.docx"; // 3. 读取本地文件流 using var fileStream = new FileStream(localFilePath, FileMode.Open); // 4. 执行上传 await graphClient.Sites[$"{siteHost}:{siteRelativePath}":] .Drives[libraryName] .Root .ItemWithPath($"{targetSubfolderPath}/{uploadFileName}") .Content .PutAsync(fileStream);
场景2:大文件(>4MB)可续传上传
适合大文件上传场景,中断后可从断点继续上传,无需从头开始:
// 初始化Graph客户端、配置参数的逻辑和小文件场景一致,此处省略 using var fileStream = new FileStream(localFilePath, FileMode.Open); // 1. 构造上传会话参数 var uploadSessionRequestBody = new Microsoft.Graph.Drives.Item.Items.Item.CreateUploadSession.CreateUploadSessionPostRequestBody { Item = new DriveItemUploadableProperties { AdditionalData = new Dictionary<string, object> { // 同名文件冲突处理:replace替换/rename自动重命名/fail报错中断 { "@microsoft.graph.conflictBehavior", "replace" } } } }; // 2. 创建上传会话 var uploadSession = await graphClient.Sites[$"{siteHost}:{siteRelativePath}":] .Drives[libraryName] .Root .ItemWithPath($"{targetSubfolderPath}/{uploadFileName}") .CreateUploadSession .PostAsync(uploadSessionRequestBody); // 3. 配置分片上传参数,分片大小建议为320KB的整数倍 var maxSliceSize = 320 * 1024 * 10; // 示例设置为3MB var fileUploadTask = new LargeFileUploadTask<DriveItem>(uploadSession, fileStream, maxSliceSize); // 可选:监听上传进度 var progress = new Progress<long>(uploadedBytes => { Console.WriteLine($"已上传:{uploadedBytes} / {fileStream.Length} 字节"); }); // 4. 启动上传 var uploadResult = await fileUploadTask.UploadAsync(progress); if (uploadResult.UploadSucceeded) { Console.WriteLine($"上传完成,文件ID:{uploadResult.ItemResponse.Id}"); }
可选:提前创建目标子文件夹
如果不确定子文件夹是否存在,可先执行以下代码创建:
var folderToCreate = new DriveItem { Name = "目标文件夹名", Folder = new Folder(), AdditionalData = new Dictionary<string, object> { { "@microsoft.graph.conflictBehavior", "fail" } } }; // 在指定父路径下创建文件夹 await graphClient.Sites[$"{siteHost}:{siteRelativePath}":] .Drives[libraryName] .Root .ItemWithPath("父文件夹路径") .Children .PostAsync(folderToCreate);
注意事项
- 权限要求:应用需提前配置
Files.ReadWrite.All或Sites.ReadWrite.All权限(根据实际场景选择应用权限/委托权限),且需管理员授权同意。 - 路径中的特殊字符需要做URL编码,避免出现定位错误。
- 若已知站点ID、库ID、子文件夹ID,可直接用ID替换路径定位方式,接口调用性能更高。
内容的提问来源于stack exchange,提问作者Ciro di Marzo
相关产品推荐
相关产品推荐

