2
votes

I want to read out the BuiltInDocumentProperties/CustomDocumentProperties of an Word document. The following Source always return 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");
        }

    }

What's wrong with the source? CustomDocumentProperties and BuiltInDocumentProperties are available and filled in the document!

1
I see this issue when trying to access them from another thread, though that doesn't seem to be what you're doing. The accepted answer still applies in this scenario.Chris

1 Answers

4
votes

I had the same issue with .docx document. One way to get through was to forget about type casting and instead keep dynamic and object as types and then the code worked. I suspect that the COM property of a .docx file is not the type described in the MSDN...

So this code captures the raw document's properties and set them in a 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)
          {

          }
      }
 }