使用C# Word Interop无法修改Word文档内置属性“Creation Date”的问题
解决Word Interop无法修改Creation Date内置属性的问题
我之前也踩过这个坑!Word的BuiltInDocumentProperties["Creation Date"]是只读属性,这就是你赋值后完全没效果的原因——而Author是可写属性,Excel的对应属性则允许直接修改,这完全是Office不同组件Interop的设计差异,没什么特别的道理,就是微软这么实现的。
下面给你两种解决方案,根据你的需求选:
方案1:修改文件系统创建时间(适合只需文件属性显示正确的场景)
你已经用到了File.SetCreationTime,但大概率是Word进程没有彻底释放文件句柄,导致修改没生效。优化你的代码,确保COM对象被完全清理:
string fullPath = null; DateTime creationDate = new DateTime(); string creatorName = null; foreach (var arg in args) { if (arg.Contains("--path")) { fullPath = arg.Substring(7); } if (arg.Contains("--creationDate")) { creationDate = DateTime.Parse(arg.Substring(15)); } if (arg.Contains("--creatorName")) { creatorName = arg.Substring(14); } } Microsoft.Office.Interop.Word.Application wordInterop = null; Microsoft.Office.Interop.Word.Document wordDoc = null; try { wordInterop = new Microsoft.Office.Interop.Word.Application(); wordDoc = wordInterop.Documents.Open(fullPath); // 修改Author属性(这部分你的代码是有效的,保留即可) wordDoc.BuiltInDocumentProperties["Author"].Value = creatorName; wordDoc.Save(); } finally { // 先关闭文档再释放 if (wordDoc != null) { wordDoc.Close(); Marshal.ReleaseComObject(wordDoc); } // 退出Word应用并释放 if (wordInterop != null) { wordInterop.Quit(); Marshal.ReleaseComObject(wordInterop); } // 强制垃圾回收,确保COM对象彻底释放文件锁 GC.Collect(); GC.WaitForPendingFinalizers(); } // 现在修改文件系统的创建时间,肯定能生效了 File.SetCreationTime(fullPath, creationDate);
这种方法能让文件资源管理器里的创建日期更新,但如果你打开Word文档的「属性→详细信息」,里面的“创建日期”还是原来的——因为那是文档内部的元数据,Interop碰不了它。
方案2:修改Word文档内部元数据(需要Open XML SDK)
如果要让Word文档自身的元数据也显示修改后的创建日期,就得用Open XML SDK,这是绕开Interop限制的最佳方式,而且不需要启动Word进程,效率更高:
- 先安装NuGet包:
DocumentFormat.OpenXml - 用以下代码修改:
using DocumentFormat.OpenXml.Packaging; // 修改文档内部元数据 using (WordprocessingDocument doc = WordprocessingDocument.Open(fullPath, true)) { var coreProps = doc.PackageProperties; coreProps.Created = creationDate; // 修改内部创建日期 coreProps.Creator = creatorName; // 同时修改作者 } // 同步修改文件系统时间 File.SetCreationTime(fullPath, creationDate);
这样处理后,不管是文件资源管理器还是Word内部的属性窗口,显示的创建日期都会是你设置的值。
最后再提一句:Excel能直接修改Creation Date是因为它的Interop实现允许这么做,Word则把这个属性锁死成只读了,这就是两者的核心区别。
内容的提问来源于stack exchange,提问作者tarcseh
相关产品推荐
相关产品推荐

