如何通过 C# 获取我刚刚插入到文档 (MS Word) 中的图片的名称和路径?

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

我有一个文档,我向该文档插入了一张图片(名称 koala.jpg 来自 C:\Data)。我想检查我是否插入了准确的图片(koala.jpg 来自 C:\Data 而不是另一张图片)。所以我希望我能得到这个插入的图片的名称和路径。我在互联网上找到了很多,但我没有解决这个问题的好主意。我在 Microsoft.Office.Interop.Word 中找到了 LinkFormat.SourceFullName 但我不知道如何使用它。我认为 LinkFormat.SourceFullName 用于 Inser Picture 类型 "Link to file"。但是我的图片是默认插入"Insert"(不是Insert Link to file)。 我希望你能给我解决问题的想法。

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 

Word 不在文档中存储此信息。它确实将原始文件的 名称 存储在 Word 打开 XML 中,但不存储原始文件路径。并且文件名没有暴露给对象模型("interop"),只能从Word Open XML中提取(可以从"interop"中读取,通过Range.WordOpenXML 属性.

如果您需要跟踪图像的整个文件路径,那么您的应用程序需要管理用于插入它的界面。 "roll your own" 对话框或利用 Word 的内置对话框。

两者都是可能的,但后者在使用 C# 时需要 PInvoke,因为对话框参数 "late-bound" 进入 Word 对象模型,因此无法通过 C# 的对象模型访问。

有关如何在 C# 中使用 Word 内置对话框的示例,请参阅此 . A list of built-in dialog boxes with their arguments can be found at https://docs.microsoft.com/en-us/office/vba/word/concepts/customizing-word/built-in-dialog-box-argument-lists-word。 return 的内置对话框参数用户选择的图片的文件路径是 Name