Search code examples
c#vstooffice-interopoffice-addins

How to get the same shape or picture in the whole powerpoint file and replace them?


I am using Visual Studio and developing an Office add-in. I need to identify same shapes and pictures and replace them.

I try to use OpenXml to do that but it doesn't seem to be able to be modified in files in use. It doesn't seem to work as an office add-in because it doesn't work with files that are already open.

And I have searched for many hours on the internet but not found a way to do that. Help me please.

Thank you


Solution

  • TL; DR: OpenXML and Office add-ins (including VSTO) are competing technologies for different use cases that may lead to runtime issues if combined. Best to stick to just one.


    I am ... developing a office add-in. I need to identify same shapes and pictures and replace them. I try to use OpenXml to do that but it doesn't seem to be able to be modified in files in use.

    OpenXML is an API for creating/reading/modifying Office documents (Office 2010+ to be exact) that adhere to the contemporary XML document format such as Word 2010. It does so by manipulating the document directly at the file level rather than using COM. In fact it does not require Word to be installed on the machine at all! This makes OpenXML a rather light-weight approach to interacting with Office documents.

    Unfortunately OpenXML (or other file-based approaches) are unsuitable for Office add-ins (VSTO or otherwise) if both are targeting the same document. This is because the document is already loaded into say Word and Word is hosting your add-in. Any attempt to modify the underlying file (including OpenXML by anything but Word or Word APIs) that represents the loaded document will encounter a:

    sharing violation

    To put this another way:

    1. In order to run your Office add-in the Office app needs to be running first. This is known as hosting
    2. Operations on Office documents orchestrated by your add-in require the document to be loaded into the Office app first
    3. No external Windows process or in-process (add-in) operation can directly change the underlying Office document file whilst it is open in the Office app. (Add-ins can indirectly save to the file using Office APIs and ask the Office app to Save though generally such APIs don't expose any raw file interfaces to the caller so the later is probably not the same thing)

    What to do?

    My recommendation is to either:

    a) use a pure OpenXML approach and discard the Office add-in or...

    b) use a pure Office add-in (VSTO) approach and discard the OpenXML code

    Considering that it seems you already have code for shapes and pictures via the OpenXML approach, perhaps option a) is the best.

    See also