如何使用SharePoint CSOM更新文件的Created、Modified等元数据属性
问题根因
代码执行无报错但字段未更新的核心原因:
- 未显式加载文件对应的
ListItemAllFields属性,字段赋值未被CSOM正确识别提交 - 普通
Update()方法会触发SharePoint内置逻辑,自动将Modified、Created字段覆盖为当前操作时间
优化代码(支持单次ExecuteQuery提交)
FileCreationInformation newFile = new FileCreationInformation(); byte[] FileContent = null; using (var webClient = new WebClient()) { webClient.Headers.Add("Authorization", authorization); FileContent = webClient.DownloadData(file.DowlnloadUrl); } newFile.ContentStream = new System.IO.MemoryStream(FileContent); newFile.Url = System.IO.Path.GetFileName(file.Name); Microsoft.SharePoint.Client.File sharepointFile = _spFolder.Files.Add(newFile); // 预加载列表项属性,排队更新操作无需立刻提交 _context.Load(sharepointFile.ListItemAllFields); // 赋值自定义时间字段 sharepointFile.ListItemAllFields["Modified"] = DateTime.Today.AddDays(-3); sharepointFile.ListItemAllFields["Created"] = DateTime.Today.AddDays(-3); // 如需更新创建人、修改人字段,放开以下注释,替换为目标用户账号 // var targetUser = _context.Web.EnsureUser("domain\\username"); // _context.Load(targetUser); // sharepointFile.ListItemAllFields["Author"] = targetUser; // sharepointFile.ListItemAllFields["Editor"] = targetUser; // 强制覆盖系统字段,不触发默认时间更新逻辑 sharepointFile.ListItemAllFields.UpdateOverwriteVersion(); // 单次提交所有操作:上传+元数据更新 _context.ExecuteQuery();
关键说明
UpdateOverwriteVersion()方法不会生成新的文件版本,同时绕过SharePoint对系统字段的自动赋值逻辑,保证自定义时间、人员字段值生效- 所有操作均先在客户端排队,最终仅调用一次
ExecuteQuery提交到服务端,符合一次性完成操作的需求 Author字段对应CreatedBy属性,Editor字段对应ModifiedBy属性,赋值前需通过EnsureUser方法获取SharePoint认可的用户对象
内容的提问来源于stack exchange,提问作者Rafa Ayadi
相关产品推荐
相关产品推荐

