将带有空格的文件地址传递给CMD

时间:2018-08-23 22:42:10

标签: c# visual-studio escaping

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

package main

import (
    "fmt"
    "bufio"
    "os"
    "strings"
)

func main() {
    fmt.Print("*A basic GoLang/Native example*\n\n")
    fmt.Print("Enter your name:\n")

    reader := bufio.NewReader(os.Stdin)
    name, _ := reader.ReadString('\n')
    name = strings.TrimSuffix(name, "\n")

    fmt.Printf("Hello, %s, how are you?", name)

    reader.ReadString('\n')

}

1 个答案:

答案 0 :(得分:0)

不知道确切的答案,但这是通过将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 /c,其中cmd是命令,而所有/*只是它的参数。

我建议您手动打开CMD.EXE,然后首先在其中尝试整个strCmdText命令。当您看到它正在运行时,请在脚本中调用它。