使用Microsoft.SharePoint.Client向SharePoint文件夹上传图片的C#实现咨询
前置准备
首先解码你提供的目标文件夹URL中的id参数,得到目标文件夹的服务器相对路径:/sites/COLBMAOpsServ/ip/01 Business Cases/PMO Tools & Information/IPA dump folder_SWP images
请提前确认你申请的App-only应用已经分配了对应站点的写入权限,否则会触发权限拒绝错误。
完整实现代码
using Microsoft.SharePoint.Client; using System.IO; public class Program { static void Main(string[] args) { string siteUrl = "https://mywebsite/sites/COLBMAOpsServ"; // 目标文件夹的服务器相对路径 string targetFolderRelativeUrl = "/sites/COLBMAOpsServ/ip/01 Business Cases/PMO Tools & Information/IPA dump folder_SWP images"; // 替换为本地待上传图片的实际路径 string localImagePath = @"C:\Users\xxx\Pictures\test.jpg"; string uploadFileName = Path.GetFileName(localImagePath); using (var cc = new AuthenticationManager().GetAppOnlyAuthenticatedContext(siteUrl, "4a30b9e9-2222-3333-45678-e59af9bf8150", "QsyzIc09Rt3bBmWk4444444444M5KpLv9LX45678990U=")) { // 验证站点连接 cc.Load(cc.Web, p => p.Title); cc.ExecuteQuery(); Console.WriteLine("已连接到站点:" + cc.Web.Title); // 获取目标文件夹对象 Folder targetFolder = cc.Web.GetFolderByServerRelativeUrl(targetFolderRelativeUrl); cc.Load(targetFolder); cc.ExecuteQuery(); // 读取本地图片流 using (FileStream fs = new FileStream(localImagePath, FileMode.Open)) { // 构造上传参数 FileCreationInformation fileCreateInfo = new FileCreationInformation { ContentStream = fs, Url = uploadFileName, Overwrite = true // 不需要覆盖同名文件可修改为false }; // 执行上传操作 Microsoft.SharePoint.Client.File uploadedFile = targetFolder.Files.Add(fileCreateInfo); cc.Load(uploadedFile); cc.ExecuteQuery(); Console.WriteLine($"图片上传成功,服务器路径:{uploadedFile.ServerRelativeUrl}"); } }; } }
注意事项
- 上传大于4MB的文件时,需要使用
StartUpload、ContinueUpload、FinishUpload分片上传接口实现,避免触发请求大小限制 - 传入的文件夹相对路径要和SharePoint实际路径完全匹配,特殊字符不要做多余转义,避免出现找不到文件夹的报错
- 如果需要给上传的图片设置自定义元数据,可以在上传完成后对
uploadedFile.ListItemAllFields属性赋值,再调用ExecuteQuery保存即可
内容的提问来源于stack exchange,提问作者maxspan
相关产品推荐
相关产品推荐

