You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用SharePoint CSOM更新文件的Created、Modified等元数据属性

CSOM更新SharePoint文件元数据解决方案

问题根因

代码执行无报错但字段未更新的核心原因:

  • 未显式加载文件对应的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 20:39:02