Search code examples
c#ms-wordvstooffice-addinsword-addins

Handling Word After Save Event for Documents Saved to SharePoint or OneDrive in VSTO AddIn


I implemented the Word After Save Event by DAVID E. CRAIG in my VSTO Word AddIn in C#.

I need the AfterSaveUiEvent to update a dictionary that contains some information about the document. The key to this dictionary is the FullName of the document.

If the document is saved to a local path there is no problem and the event is fired each time. The thread waits inside the while (oWord.BackgroundSavingStatus > 0) until the document is saved.

The problem only occurs when I save a document to SharePoint or OneDrive.

I found this through debugging:

  • The While loop that checks if BackgroundSavingStatus > 0 is never entered. It seems that BackgroundSavingStatus does not work correctly with OneDrive or SharePoint.
  • This causes doc.Saved to be accessed too early. Either doc.Saved is still set to false and the event is not fired at all, or an exception is thrown when doc.Saved is accessed, causing IsClosing to be set to true even though the document has not been closed.

Is there a way to wait until the SharePoint or OneDrive saving process is complete similar to while (oWord.BackgroundSavingStatus > 0)?


Solution

  • The problem is due to the co-authoring capabilities of SharePoint and OneDrive, which keeps 'auto-save' persistently enabled. As David E. Craig mentioned on his blog:

    The problem is that auto-save is now persistent with Office coauthoring capabilities. There is really no finite event for saving except the first save of a new document when documents are in SharePoint or OneDrive.

    Possible solutions:

    1. Ribbon override: One possible solution is to override the save button with a custom event handler. This would allow the user initiated save action to be captured.

    2. Dirty filename timer hack: Another suggestion from David is to detect new documents and start a timer that monitors when the full path of the document is available. This hack simulates an "after save" event by checking when the file is assigned a full path after its first save.

    My approach: After considering these solutions, I took a step back to re-evaluate why I needed the AfterUISave event. Instead of trying to hook into SharePoint or OneDrive's save process, I found an alternative approach to meet my needs without relying on the AfterUISave event.

    Thanks to David E. Craig