无SharePoint站点首页权限时,如何用C# CSOM上传文件至子文件夹
问题解决及文件上传实现方案
核心问题分析
你的代码报错原因是传入ClientContext的URL是SharePoint列表视图的URL(包含AllItems.aspx和RootFolder参数),而ClientContext要求传入的是站点集合(Site Collection)或子站点(Subsite)的根URL,不是具体页面或视图的URL。此外,你要上传的子文件夹实际属于OEM-inteltech-FabrinetShared站点,而非inteltechShared站点,这也是导致权限和访问问题的原因之一。
解决步骤及代码实现
1. 修正站点URL
使用目标文件夹所属的站点根URL:https://inteltechcorp.sharepoint.com/sites/OEM-inteltech-FabrinetShared
2. 直接访问目标文件夹
由于你无站点首页访问权限,但能访问指定子文件夹,可通过服务器相对路径直接定位到目标文件夹,无需通过文档库标题获取(后者可能需要站点级权限)。
3. 完整上传代码
using System.IO; using System.Security; using Microsoft.SharePoint.Client; public void UploadExcelToSharePoint(string userName, string password, string localExcelPath) { // 正确的站点根URL string siteUrl = "https://inteltechcorp.sharepoint.com/sites/OEM-inteltech-FabrinetShared"; // 目标文件夹的服务器相对路径(从站点根开始) string targetFolderRelativeUrl = "/sites/OEM-inteltech-FabrinetShared/Shared Documents/inteltech - OEM Transfer Project/BC Kitting - Mirror from Fileshare"; using (var context = new ClientContext(siteUrl)) { // 设置凭据 context.Credentials = new SharePointOnlineCredentials(userName, GetSecureString(password)); try { // 获取目标文件夹 Folder targetFolder = context.Web.GetFolderByServerRelativeUrl(targetFolderRelativeUrl); context.Load(targetFolder); context.ExecuteQuery(); // 读取本地Excel文件 string fileName = Path.GetFileName(localExcelPath); byte[] fileContent = File.ReadAllBytes(localExcelPath); // 上传文件到目标文件夹(覆盖已存在的同名文件) FileCreationInformation fileCreationInfo = new FileCreationInformation { Content = fileContent, Url = fileName, Overwrite = true }; Microsoft.SharePoint.Client.File uploadedFile = targetFolder.Files.Add(fileCreationInfo); context.Load(uploadedFile); context.ExecuteQuery(); Console.WriteLine($"文件 {fileName} 上传成功!"); } catch (ClientRequestException ex) { Console.WriteLine($"上传失败:{ex.Message}"); } } } // 辅助方法:将字符串密码转为SecureString private SecureString GetSecureString(string password) { SecureString securePassword = new SecureString(); foreach (char c in password) { securePassword.AppendChar(c); } return securePassword; }
关键说明
- 站点URL正确性:必须使用目标文件夹所属站点的根URL,而非列表视图URL。
- 服务器相对路径:确保路径准确对应你要上传的子文件夹,可从浏览器地址栏的
RootFolder参数提取并解码后使用。 - 权限验证:你的账号需具备目标文件夹的写入权限,由于你已能访问该文件夹,此条件已满足。
- 依赖包:确保项目已安装
Microsoft.SharePointOnline.CSOMNuGet包(版本建议使用最新稳定版)。
内容的提问来源于stack exchange,提问作者carlwang
相关产品推荐
相关产品推荐

