使用Word interop设置自定义文档属性

F.P*_*F.P 6 interop vsto ms-word office-addins office-2010

我想在我的C#代码中设置我正在创建的word文档的一些自定义文档属性.为此,我按照这篇MSDN文章提出了这段代码:

using Word = Microsoft.Office.Interop.Word; // Version 12.0.0.0
word = new Word.Application();
word.Visible = false;
Word._Document doc = word.Documents.Add(ref missing, ref missing, ref missing, ref missing);
logger.Info("Setting document properties");
Core.DocumentProperties properties = (Core.DocumentProperties)doc.BuiltInDocumentProperties;
properties["Codice_documento"].Value = args[3];
properties["Versione_documento"].Value = args[4];
Run Code Online (Sandbox Code Playgroud)

不幸的是,每当它到达代码时我都会收到此错误:

HRESULT:0x80004002(E_NOINTERFACE)

这是为什么?我完全按照我的MSDN描述使用接口,为什么它不起作用?

我正在使用Interop for office 2010和.net 3.5

Sli*_*SFT 5

你需要使用CustomDocumentProperties,而不是BuiltInDocumentProperties.有关在Word中使用自定义文档属性(以及此处的MSDN视频)的信息,请参阅MSDN参考.您还需要检查属性是否存在并在尝试分配其值之前创建它.

Core.DocumentProperties properties = (Core.DocumentProperties)this.Application.ActiveDocument.CustomDocumentProperties;
if (properties.Cast<DocumentProperty>().Where(c => c.Name == "DocumentID").Count() == 0)
  properties.Add("DocumentID", false, MsoDocProperties.msoPropertyTypeString, Guid.NewGuid().ToString());
var docID = properties["DocumentID"].Value.ToString();
Run Code Online (Sandbox Code Playgroud)


F.P*_*F.P 5

在MSDN论坛上提出这个问题后,答案就出来了。问题是,我尝试的方法是 VSTO 特有的。由于我的不知情,我混淆了VSTO、Interop等定义,从而给这个问题贴上了错误的标签。

现在可以使用以下代码运行:

logger.Info("Setting document properties");
object properties = doc.CustomDocumentProperties;
Type propertiesType = properties.GetType();

object[] documentCodeProperty = { "Codice_documento", false, Core.MsoDocProperties.msoPropertyTypeString, args[3] };
object[] documentVersionPoperty = { "Versione_documento", false, Core.MsoDocProperties.msoPropertyTypeString, args[4] };

propertiesType.InvokeMember("Add", BindingFlags.InvokeMethod, null, properties, documentCodeProperty);
propertiesType.InvokeMember("Add", BindingFlags.InvokeMethod, null, properties, documentVersionPoperty);
Run Code Online (Sandbox Code Playgroud)