首页 > 解决方案 > 将带空格的文件地址传递给 CMD

问题描述

我有以下代码,只要我的地址在文件夹名称中没有任何空格,它就可以正常工作。我知道 oFileLocation 中的空格是导致我出现问题的原因,并且我知道我需要将其用双引号括起来,但无论我如何转义字符,CMD.EXE 都会告诉我“'/c' 不被识别为内部或外部命令....”我需要如何更改 strCmdText 以处理 oFileLocation 中的空格?

oFileLocation = \\data\shares\folder1\file.iso
strCmdText = "/c \"C:\\Program Files\\7-Zip\\7z.exe\" x -tiso -y " + oFileLocation + 
    " -o" + oDownloadDirectory + "\\" + oFileNameReplaced;
ProcessStartInfo startInfo = new ProcessStartInfo("CMD.exe");
startInfo.WindowStyle = ProcessWindowStyle.Maximized;
startInfo.Arguments = strCmdText;
Process.Start(startInfo).WaitForExit();

标签: c#visual-studioescaping

解决方案


不知道确切的答案,但这是我通过写入cmd /?CMD.EXE快速发现的

If /C or /K is specified, then the remainder of the command line after
the switch is processed as a command line, where the following logic is
used to process quote (") characters:

1.  If all of the following conditions are met, then quote characters
on the command line are preserved:

- no /S switch
- exactly two quote characters
- no special characters between the two quote characters,
  where special is one of: &<>()@^|
- there are one or more whitespace characters between the
  two quote characters
- the string between the two quote characters is the name
  of an executable file.

2.  Otherwise, old behavior is to see if the first character is
a quote character and if so, strip the leading character and
remove the last quote character on the command line, preserving
any text after the last quote character.

因为你/c不被认为是一个命令,因为它实际上是一个参数。你需要使用cmd /cwherecmd是一个命令,同时 all/*只是它的参数。

我建议您手动打开 CMD.EXE 并首先在那里尝试您的整个strCmdText命令。当您看到它正在工作时,请在脚本中调用它。


推荐阅读