gpt4 book ai didi

c# - 使用 Word 2010 读取 BuiltInDocumentProperties/CustomDocumentProperties 始终为空?

转载 作者:行者123 更新时间:2023-11-30 21:55:56 27 4
gpt4 key购买 nike

我想读出 Word 文档的 BuiltInDocumentProperties/CustomDocumentProperties。以下源总是返回 null :-(

using Microsoft.Office.Core;
using Word = Microsoft.Office.Interop.Word;
.....
private void toolStripMenuItemTmp_Click(object sender, EventArgs e)
{
Word.Application word = new Word.Application();
Word.Document document = word.Documents.Open(@"C:\Users\fillibuster\Desktop\docproperty.docx");
DocumentProperties properties = (DocumentProperties)document.CustomDocumentProperties;
if (properties != null)
{
foreach (Microsoft.Office.Core.DocumentProperty item in properties)
{
MessageBox.Show(item.Name.ToString() + item.Value.ToString());
}
}
else
{
MessageBox.Show("null");
}

}

来源有什么问题? CustomDocumentProperties 和 BuiltInDocumentProperties 可用并填写在文档中!

最佳答案

我对 .docx 文档有同样的问题。一种解决方法是忘记类型转换,而是将 dynamicobject 保留为类型,这样代码就可以工作了。我怀疑 .docx 文件的 COM 属性不是 MSDN 中描述的类型...

因此这段代码捕获原始文档的属性并将它们设置在字典中。

  try
{
BuiltInDocumentProperties = new Dictionary<string, string>();
var builtinProps = Doc.BuiltInDocumentProperties; // don't strong cast this or you will get null
SetBuiltInProperty(builtinProps, "Title");
SetBuiltInProperty(builtinProps, "Keywords");
}
catch (Exception e)
{
// Ignorer l'erreur
Log.Warn("Erreur inattendue à la lecture des propriétés internes du document", e);
}

IDictionary<string, string> BuiltInDocumentProperties { get; set; }

internal void SetBuiltInProperty(dynamic builtInProps, string property)
{
if (builtInProps != null)
{
try
{
var prop = builtInProps[property];
if (prop != null)
{
string str = prop.Value.ToString();
BuiltInDocumentProperties[property] = str;
}
}
catch (RuntimeBinderException)
{
// Property is missing
}
catch (COMException)
{

}
}
}

关于c# - 使用 Word 2010 读取 BuiltInDocumentProperties/CustomDocumentProperties 始终为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31826865/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com