Reading the BuiltInDocumentProperties modifies the Word document

Add-in Express™ Support Service
That's what is more important than anything else

Reading the BuiltInDocumentProperties modifies the Word document
 
abel


Guest


Hello,

when I try to read the BuiltInDocumentProperties of a Word document and close the document (without changing anything in the document), I get a message asking if I want to save my changes.
I have found out that reading the BuiltInDocumentProperties in Word causes this problem. By the way, the problem doesn't occur in Excel.

Thanks.

My code below:

void ReadProps()
{
	Word.Document document = null;
	Word.Documents documents = null;
	Microsoft.Office.Core.DocumentProperties docprops = null;
	
	try
	{
		if (WordApp != null)
		{
			int count = 0;
			documents = WordApp.Documents;
			count = documents.Count;
			if (documents != null) Marshal.ReleaseComObject(documents);

			if (count > 0)
			{
				try
				{
					document = WordApp.ActiveDocument;
					if (document != null)
					{
						// this line causes the problem
						docprops = document.BuiltInDocumentProperties as Microsoft.Office.Core.DocumentProperties;
					}
				}
				catch (Exception ex)
				{
					// ...
				}
			}
			
			if (docprops != null && docprops["Keywords"] != null && docprops["Keywords"].Value != null)
			{
				// ...
			}
		}
	}
	catch (COMException)
	{
		// ...
	}
	catch (Exception ex)
	{
		// ...
	}
	finally
	{
		if (docprops != null) Marshal.ReleaseComObject(docprops);
		if (document != null) Marshal.ReleaseComObject(document);
	}
	
}
Posted 17 Mar, 2021 07:16:21 Top
Andrei Smolin


Add-in Express team


Posts: 18829
Joined: 2006-05-11
Hello,


Office.DocumentProperties documentProperties = null;
Office.DocumentProperty documentProperty = null;
...
bool isSaved = WordDocument.Saved; 
documentProperties = WordDocument.BuiltInDocumentProperties as Office.DocumentProperties;
if (documentProperties != null)
{
    if (isSaved && WordDocument.Saved != true) WordDocument.Saved = true; 
    try
    {
        // process documentProperties
        // get documentProperty and check its value
    }
    finally
    {
        Marshal.ReleaseComObject(documentProperties);
        if (documentProperty != null) Marshal.ReleaseComObject(documentProperty);
        // release COM objects (if any) created in the try block above
    }
}



Andrei Smolin
Add-in Express Team Leader
Posted 17 Mar, 2021 07:46:10 Top
abel


Guest


Hello Andrei,
thanks for your quick reply. This is exactly what I was looking for.
I have already tested with your code and it works fine.

Regards
Posted 18 Mar, 2021 01:46:21 Top
Andrei Smolin


Add-in Express team


Posts: 18829
Joined: 2006-05-11
You are welcome!


Andrei Smolin
Add-in Express Team Leader
Posted 18 Mar, 2021 10:12:49 Top