C#上传文件到SharePoint时遭遇400错误及文件无内容问题
一、SaveBinaryDirect上传后文件无内容的修复
你的SaveBinaryDirect代码里,MemoryStream写入字节数组后,指针停在流的末尾,导致SharePoint读取不到任何内容。只需在调用SaveBinaryDirect前把流的Position重置为0即可解决:
string siteUrl = "https://xxx.sharepoint.com/sites/my-site/"; string username = "xx@yy.com"; string password = "ss@sf"; string filePath = "filePath.xlsx"; using (ClientContext context = new ClientContext(siteUrl)) { var securePWD = new SecureString(); foreach (char c in password) securePWD.AppendChar(c); context.Credentials = new SharePointOnlineCredentials(username, securePWD); FileInfo fileInfo = new FileInfo(filePath); byte[] fileContent = File.ReadAllBytes(filePath); using (MemoryStream memoryStream = new MemoryStream(fileContent)) { // 关键:重置流指针到起始位置 memoryStream.Position = 0; // 注意:这里要传入完整的服务器相对路径,不能用占位符 Microsoft.SharePoint.Client.File.SaveBinaryDirect(context, "/sites/my-site/Shared Documents/" + fileInfo.Name, memoryStream, true); } }
另外注意SaveBinaryDirect的第二个参数必须是完整的服务器相对路径,比如/sites/my-site/Shared Documents/文件名.xlsx,不能使用占位符/ServerRelativeURL/。
二、FileCreationInformation报HTTP 400错误的修复
400错误通常由路径错误、权限问题或资源名称不匹配导致,结合你连读取列表都报错的情况,重点检查以下几点:
1. 服务器相对路径必须完整
GetFolderByServerRelativeUrl需要的是从根站点开始的完整路径,而非相对当前站点的路径。比如你的站点是https://xxh.sharepoint.com/sites/my-Test-Site/,那么Shared Documents/myFolder的完整服务器相对路径应为/sites/my-Test-Site/Shared Documents/myFolder。
2. 确认文档库的真实标题
你用Lists.GetByTitle("Documents")报错,说明站点内可能没有标题为"Documents"的文档库——默认文档库的标题通常是"Shared Documents",或者你可能修改过库名称。可以通过站点设置查看库的真实标题,或改用路径获取库以避免标题错误:
// 用路径获取文档库,无需依赖标题 List documentsLibrary = context.Web.Lists.GetByUrl("/sites/my-Test-Site/Shared Documents"); context.Load(documentsLibrary); context.ExecuteQuery();
3. 修正后的FileCreationInformation上传代码
string siteUrl = "https://xxh.sharepoint.com/sites/my-Test-Site/"; string username = "xx@yy.com"; string password = "sad@fds"; // 使用完整的服务器相对路径 string serverRelativeUrl = "/sites/my-Test-Site/Shared Documents/myFolder"; string filePath = "filePath.xlsx"; using (ClientContext context = new ClientContext(siteUrl)) { var securePWD = new SecureString(); foreach (char c in password) securePWD.AppendChar(c); context.Credentials = new SharePointOnlineCredentials(username, securePWD); var fileCreationInfo = new FileCreationInformation { Content = System.IO.File.ReadAllBytes(filePath), Overwrite = true, Url = Path.GetFileName(filePath) }; var targetFolder = context.Web.GetFolderByServerRelativeUrl(serverRelativeUrl); var uploadFile = targetFolder.Files.Add(fileCreationInfo); context.Load(uploadFile); context.ExecuteQuery(); }
4. 权限排查
如果以上调整后仍报错,检查当前账号是否拥有目标站点的编辑权限,确保账号能正常访问目标文档库及文件夹。
内容的提问来源于stack exchange,提问作者Jaspreet Singh

