C# Microsoft.Office.Interop.Word cant open path with spaces

0

I'm trying to use Microsoft.Office.Interop.Word to open and resave MS word documents but whenever it runs into a path with spaces it freaks out even if I embed quotes around the string using

"\"" + string + "\""

or something like that. Copy pasting the exact path that it outputs after "Processing " into my terminal does open up the PDF in my default program so I know the path is good and that a normal CMD shell can open it. The full error is as follows

Processing "C:/Users/me/Documents/DocTesting/!Fine.pdf"
Saving as "C:/Users/me/Documents/DocTesting/!Fine.docx"
Time elapsed: 00:00:01.1499644
Processing "C:/Users/me/Documents/DocTesting/!Not Okay.pdf"
 (C:\//Users/me/Documents/DocTesting...) (0x800A1436): Sorry, we couldn't find your file. Was it moved, renamed, or deleted?
at Microsoft.Office.Interop.Word.Documents.Open(Object& FileName, Object& ConfirmConversions, Object& ReadOnly, Object& AddToRecentFiles, Object& PasswordDocument, Object& PasswordTemplate, Object& Revert, Object& WritePasswordDocument, Object& WritePasswordTemplate, Object& Format, Object& Encoding, Object& Visible, Object& OpenAndRepair, Object& DocumentDirection, Object& NoEncodingDialog, Object& XMLTransform)
   at Testing.DocumentConverter.convDoc(String filename, String inPath, String outPath)
Unhandled Exception: System.Runtime.InteropServices.COMException: The object invoked has disconnected from its clients. (Exception from HRESULT: 0x80010108 (RPC_E_DISCONNECTED))
   at Microsoft.Office.Interop.Word.DocumentClass.get_Application()
   at Testing.DocumentConverter.convDoc(String filename, String inPath, String outPath)
   at Testing.Program.Main(String[] args)

and the code that caused the error is as follows:

string docstring = "\"" + inPath + filename + "\"";
Console.WriteLine("Processing {0}", docstring);
doc = wordApp.Documents.Open(docstring, (object)false, ref readOnly, 
ref missing, ref  missing, ref missing, ref missing, 
ref missing, ref missing, ref missing, ref missing, 
(object)isVisible,ref missing, ref missing, ref missing, ref missing);

IT TURNS OUT WINDOWS IS FINE WITH YOU USING / IN PATHS UP UNTIL YOU INTERACT WITH WORD, THEN IT HAS TO BE \\

c#
ms-word
asked on Stack Overflow Oct 9, 2018 by Xander May • edited Oct 9, 2018 by Xander May

1 Answer

1

Use Path.GetFullPath() on the filename you create to get the correct full filename with \ as the directory separator. Your problem is that / works on a call to the Windows API but it does not work in a command line. It's the command processor that uses / as a command line option.

You should also use Path.Combine() to combine each part of the path you're building. You may be right with the string concatenation, but if you're not, that will break it.

Documents.Open() does work fine on filenames with spaces in it.

answered on Stack Overflow Oct 10, 2018 by David Thielen

User contributions licensed under CC BY-SA 3.0