![](/img/trans.png)
[英]C# how to run a process(with arguments) through an administrator elevated cmd
[英]C# run process with multiple spaces in arguments
我正在嘗試啟動一個在參數中包含多個空格的進程。 傳遞的參數是動態構建的。 例如:
// 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();
這不起作用,因為第一個空格之外的任何文本都將被忽略。 我將收到一條消息,例如“C:\\My”不是內部或外部命令、可運行的程序或批處理文件。
我想圍繞參數添加括號,如所指出的在這里,但沒有奏效。 這樣做的正確方法是什么?
您可能必須在單個參數中可能包含空格的任何內容周圍添加進一步的雙引號。 通常一個空格表示一個論點的結束。 因此,為了保留這一點,您必須將字符串放入雙引號中。
所以 consolePath 實際上應該是這樣的:
var consolePath = "\"C:\\My Path....exe\"";
除了以前的答案, @
可以用來避免\\\\
這樣的:
@"""C:\My Path\nunit3-console.exe"""
或:
"\"" + @"C:\My Path\nunit3-console.exe" + "\""
關於@
更多信息: C# 中字符串前面的@ 是什么?
在搜索了兩天的工作字符串后,我終於找到了它。
只需像這樣包裝字符串:
string Arguments = "/c " "path" --argument " ";
string Arguments = "/c \""path" --argument \"";
注意第一個字符串中的粗引號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.