System.Runtime.InteropServices.COMException 使用 Interop Word document.SaveAs 方法时

System.Runtime.InteropServices.COMException when using Interop Word document.SaveAs method

本质上,我需要创建一个 PDF 存档器,将 MailItem 的内容保存到 PDF 文件中。 代码如下:

        mailItem.BodyFormat = Outlook.OlBodyFormat.olFormatHTML;
        string pdfPath = Path.Combine(fullPath + fileName + ".pdf");
        Microsoft.Office.Interop.Word.Document doc = mailItem.GetInspector.WordEditor;
        doc.SaveAs(pdfPath, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF);

.SaveAs 方法出现异常。我基本上把它归结为,它与文件路径有关,因为我尝试将文件路径更改为更短,但没有发生异常。问题是,它必须位于较长的文件路径结构中。我确实也考虑过它可能达到了文件路径的最大长度 (255),但是根据 运行 pdfPath.Length 可以看出,长度是 81.

有没有人有什么想法?

我对此进行了更多研究,发现在处理文件路径时,您可以轻松地使用单个 / 来导航路径,例如:C:/User/Desktop.

是这样的,UNTIL您使用的是 Word 文档。 Word 不喜欢单 /,但更喜欢双 \。所以,C:/User/Desktop 变成了 C:\User\Desktop.

我之所以这样说,是因为虽然有文件路径最大长度,但我没有达到它。

问题似乎是因为文件夹名称中有一个 space,例如:C:/User/Desktop/Folder Name.

然后我改用双反斜杠,效果很好。