usr*_*260 5 c# windows command-line command escaping
我正在尝试启动一个在参数中包含多个空格的进程。传递的参数是动态构建的。例如:
// These three strings will be built dynamically
string consolePath = "C:\\My Path\\nunit3-console.exe"
string dll = "C:\\My Path\\My.Test.dll"
string where = "--where \"test == My.Test.Example \""
string cmdText = $" \"{consolePath }\" \"{dll}\" {where}";
//cmdText = "\"C:\\My Path\\nunit3-console.exe\" \"C:\\My Path\\My.Test.dll\" --where \"test == My.Test.Example \""
var processInfo = new ProcessStartInfo("cmd.exe", $"/c {cmdText}");
processInfo.CreateNoWindow = false;
Process process = Process.Start(processInfo);
process.WaitForExit();
process.Close();
Run Code Online (Sandbox Code Playgroud)
这不起作用,因为第一个空格之外的任何文本都将被忽略。我将收到一条消息,例如“C:\My”不是内部或外部命令、可运行的程序或批处理文件。
我想围绕参数添加括号,如所指出的在这里,但没有奏效。这样做的正确方法是什么?
您可能必须在单个参数中可能包含空格的任何内容周围添加进一步的双引号。通常,空格意味着论证的结束。因此,为了保留这一点,您\xc2\xb4d 必须将字符串放入双引号中。
\n\n所以consolePath实际上应该是这样的:
\n\nvar consolePath = "\\"C:\\\\My Path....exe\\"";\nRun Code Online (Sandbox Code Playgroud)\n