我想读出Word文档的BuiltInDocumentProperties / CustomDocumentProperties。以下Source始终返回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文档有同样的问题。一种解决方法是忘记类型转换,而是将dynamic
和object
保留为类型,然后代码才能工作。我怀疑.docx文件的COM属性不是MSDN中描述的类型...
因此,此代码捕获了原始文档的属性并将其设置在Dictionary中。
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# - 读取BuiltInDocumentProperties/CustomDocumentProperties在Word 2010中是否始终为null?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31826865/