C#Microsoft.Office.Interop.Word无法打开带空格的路径

时间:2018-10-09 19:45:15

标签: c# ms-word

我正在尝试使用Microsoft.Office.Interop.Word打开和重新保存MS Word文档,但是每当遇到带空格的路径时,它都会吓跑,即使我使用

"\"" + string + "\""

或类似的东西。将“正在处理”之后输出的确切路径复制粘贴到我的终端中,会在默认程序中打开PDF,因此我知道该路径是好的,并且普通的CMD Shell可以打开它。完整错误如下

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)

和导致错误的代码如下:

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);

在您与Word交互之前,使用/逐步使用Windows可以使您的Windows变得完美,然后必须\\

2 个答案:

答案 0 :(得分:1)

在创建的文件名上使用Path.GetFullPath()以获取正确的完整文件名,并以\作为目录分隔符。您的问题是/在调用Windows API时起作用,但是在命令行中却不起作用。是使用/作为命令行选项的命令处理器。

您还应该使用Path.Combine()组合所构建路径的每个部分。您可能会正确使用字符串连接,但如果不正确,则会破坏它。

Documents.Open()在带有空格的文件名上可以正常工作。

答案 1 :(得分:0)

尝试在kernel32.dll中使用GetShortPathName。下面的示例有所不同,您必须针对问题进行调整。

using System;
using System.Runtime.InteropServices;

// ...
    static void Main(string[] args)
    {
        string longName = @"D:\Notebooks\Diary";
        char[] buffer = new char[1024];

        long length = GetShortPathName(longName, buffer, buffer.Length);

        string shortName = new string(buffer);
        Console.WriteLine(shortName);
        Console.WriteLine(shortName.Substring(0, (int)length));

        Console.Write("Press any key to quit . . . ");
        Console.ReadKey(true);
    }

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern uint GetShortPathName(string lpszLongPath, char[] lpszShortPath, int cchBuffer);