使用C#操作SharePoint添加附件遇权限拒绝异常求助
问题描述
用C#开发SharePoint相关功能,表单数据可正常保存至SharePoint列表,但添加附件时抛出权限拒绝异常:
"Access denied. You do not have permission to perform this action or access this resource."
异常堆栈信息:at Microsoft.SharePoint.Client.ClientRequest.ProcessResponseStream(Stream responseStream) at Microsoft.SharePoint.Client.ClientRequest.ProcessResponse() at Microsoft.SharePoint.Client.ClientRequest.ExecuteQueryToServer(ChunkStringBuilder sb) at Microsoft.SharePoint.Client.ClientContext.ExecuteQuery() at Skoda_DCMS.DAL.IDCardDAL.d__12.MoveNext() in D:\07-July-2023\eForms_Skoda_UAT_CHECK\eForms_Skoda\Skoda_DCMS\DAL\IDCardDAL.cs:line 440附件上传代码:
if (file != null) { int attachmentID = RowId; string path = file.FileName; path = path.Replace(" ", ""); string FileName = path; List docs = web.Lists.GetByTitle(listName); ListItem itemAttach = docs.GetItemById(attachmentID); var attInfo = new AttachmentCreationInformation(); attInfo.FileName = FileName; byte[] fileData = null; using (var binaryReader = new BinaryReader(file.InputStream)) { fileData = binaryReader.ReadBytes(file.ContentLength); } attInfo.ContentStream = new MemoryStream(fileData); Attachment att = itemAttach.AttachmentFiles.Add(attInfo); //Add to File _context.Load(att); _context.ExecuteQuery(); }已检查过SharePoint列表的权限设置,且使用其他账号登录可正常保存附件。
排查与解决建议
检查目标列表项的独立权限
列表权限正常不代表单个列表项权限无特殊设置。进入对应列表项的权限设置页面,确认当前账号拥有「编辑项目」或更高权限,避免列表项被单独设置了限制权限。验证账号的附件操作权限
确认当前账号的权限级别中包含「添加/删除附件」的具体权限。在列表权限级别配置里,检查对应权限组是否勾选了「管理列表项权限」或「添加附件」(具体名称因SharePoint版本略有差异)。排查附件存储目录的权限
SharePoint附件实际存储在列表的Lists/{ListName}/Attachments/{ItemId}目录下,需确认当前账号对该文件夹拥有写入权限。可通过SharePoint界面导航到该文件夹,查看并调整权限设置。确认代码上下文身份有效性
检查代码中_context使用的身份是否为当前操作用户的有效凭证。若使用服务账号或应用程序池身份,需验证该账号对目标列表项的权限;若为用户凭证,排查是否存在凭证缓存导致身份不匹配的情况。代码逻辑优化验证
- 确认
RowId对应的列表项真实存在,无效项可能触发类似权限异常提示。 - 在添加附件前,先执行
_context.Load(itemAttach); _context.ExecuteQuery();确保列表项被正确加载,避免上下文未同步导致的权限验证错误。
- 确认
内容的提问来源于stack exchange,提问作者Prashant Kuppili
相关产品推荐
相关产品推荐

