Retrieve application property values from a word processing document
This topic shows how to use the classes in the Open XML SDK for Office to programmatically retrieve an application property from a Microsoft Word document, without loading the document into Word. It contains example code to illustrate this task.
Retrieving Application Properties
To retrieve application document properties, you can retrieve the ExtendedFilePropertiesPart property of a WordprocessingDocument object, and then retrieve the specific application property you need. To do this, you must first get a reference to the document, as shown in the following code.
using (WordprocessingDocument document = WordprocessingDocument.Open(fileName, false))
{
Given the reference to the WordprocessingDocument object, you can retrieve a reference to the ExtendedFilePropertiesPart property of the document. This object provides its own properties, each of which exposes one of the application document properties.
if (document.ExtendedFilePropertiesPart is null)
{
throw new ArgumentNullException("ExtendedFilePropertiesPart is null.");
}
var props = document.ExtendedFilePropertiesPart.Properties;
Once you have the reference to the properties of ExtendedFilePropertiesPart, you can then retrieve any of the application properties, using simple code such as that shown
in the next example. Note that the code must confirm that the reference to each property isn't null
of Nothing
before retrieving its Text
property. Unlike core properties, document properties aren't available if you (or the application) haven't specifically given them a value.
if (props.Company is not null)
Console.WriteLine("Company = " + props.Company.Text);
if (props.Lines is not null)
Console.WriteLine("Lines = " + props.Lines.Text);
if (props.Manager is not null)
Console.WriteLine("Manager = " + props.Manager.Text);
Sample Code
The following is the complete code sample in C# and Visual Basic.
using DocumentFormat.OpenXml.Packaging;
using System;
static void GetApplicationProperty(string fileName)
{
using (WordprocessingDocument document = WordprocessingDocument.Open(fileName, false))
{
if (document.ExtendedFilePropertiesPart is null)
{
throw new ArgumentNullException("ExtendedFilePropertiesPart is null.");
}
var props = document.ExtendedFilePropertiesPart.Properties;
if (props.Company is not null)
Console.WriteLine("Company = " + props.Company.Text);
if (props.Lines is not null)
Console.WriteLine("Lines = " + props.Lines.Text);
if (props.Manager is not null)
Console.WriteLine("Manager = " + props.Manager.Text);
}
}