Search code examples
c#ms-wordoffice-interop

How to get the name and the path of the picture I've just inserted to document (MS Word) by C#?


I have a document and I insert a picture (name koala.jpg from C:\Data) to this document. I want to check that I inserted the exactly picture (koala.jpg from C:\Data not another picture). So I hope I will get the name and the path of this picture that was inserted. I found a lot on the Internet but I don't have any good idea to fix this problem. I found out LinkFormat.SourceFullName in Microsoft.Office.Interop.Word but I don't know how to use it. I think LinkFormat.SourceFullName is used for Inser Picture type "Link to file". But my picture is inserted at default "Insert" (not Insert Link to file). I hope you can give me the idea to fix my problem.

enter image description here

Microsoft.Office.Interop.Word.Application oWord = (Microsoft.Office.Interop.Word.Application)w;
_activeDoc = oWord.ActiveDocument; 

MessageBox.Show(_activeDoc.InlineShapes[1].LinkFormat.SourceFullName.ToString());//is error 

Solution

  • Word does not store this information in the document. It does store the name of the original file in the Word Open XML, but not the original file path. And the file name is not exposed to the object model ("interop"), it can only be extracted from the Word Open XML (which can be read from the "interop", via the Range.WordOpenXML property.

    If you need to trace the entire file path of an image then your application needs to manage the interface used to insert it. Either "roll your own" dialog box or leverage Word's built-in dialog box.

    Both are possible, but the latter requires PInvoke when using C# as the dialog box arguments are "late-bound" into the Word object model and thus not accessible via the object model for C#.

    For an example on how to use Word's built-in dialog boxes in C#, see this Stack Overflow answer. A list of built-in dialog boxes with their arguments can be found at https://learn.microsoft.com/en-us/office/vba/word/concepts/customizing-word/built-in-dialog-box-argument-lists-word. The built-in dialog box argument to return the file path for the picture the user selected is Name.