簡體   English   中英

使用 C# 中的參數和多個命令執行 .exe

[英]executing .exe with argument and multiple commands from C#

我目前正在嘗試將我編寫的 bash 腳本“轉換”為 C#。 這個腳本在 shell 中啟動一個程序,然后在這個 shell 中執行一些命令,看起來類似於:

cd /$MYPATH
./executible -s << EOF
start_source_probe -hardware_name "USB" -device_name "@1: EP3C(10|5)"
write_source_data -instance_index 0 -value "11111"
write_source_data -instance_index 0 -value "10111"
write_source_data -instance_index 0 -value "00111"
exit
EOF

現在我想使用 Visual Studio C# 做同樣的事情。 目前我的嘗試是這樣的:

ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.WorkingDirectory = "pathToExe\\";
startInfo.FileName= "executible.exe";
startInfo.Arguments= "-s";
//startInfo.UseShellExecute = false;
//startInfo.RedirectStandardInput = true;
Process proc = new Process();
proc.StartInfo = startInfo;
proc.Start();
//StreamWriter myStreamWriter = proc.StandardInput;
//Console.WriteLine("start_source_probe - hardware_name \"USB\" -device_name \"@1: EP3C(10|5)\"");
//Console.WriteLine("write_source_data -instance_index 0 -value \"11111\"");
proc.WaitForExit();

激活注釋后(因此在代碼中使用“//”)我設法打開了外殼程序(-s 代表外殼程序),但我想知道如何在此外殼程序中另外執行命令。 我設法用這樣的東西執行了多個命令(只要我不啟動 shell,因為我猜目標輸出不同)

const string strCmdText = "/C command1&command2";
Process.Start("CMD.exe", strCmdText);

如果有人能告訴我如何添加參數“-s”並在啟動的進程中執行命令,我將不勝感激。

我不確定我是否理解你的問題,但你可以在你的 c# 代碼之外創建一個批處理文件,並從你的 c# 代碼中調用它,如下所示:

System.Diagnostics.ProcessStartInfo ProcStartInfo = new System.Diagnostics.ProcessStartInfo("cmd");
ProcStartInfo.RedirectStandardOutput = true;
ProcStartInfo.UseShellExecute = false;
ProcStartInfo.CreateNoWindow = false;
ProcStartInfo.RedirectStandardError = true;
System.Diagnostics.Process MyProcess = new System.Diagnostics.Process();
ProcStartInfo.Arguments = "/c start /wait batch.bat ";
MyProcess.StartInfo = ProcStartInfo;
MyProcess.Start();
MyProcess.WaitForExit();

我添加了/wait以便您的 c# 代碼將等待您的批處理完成,以追求 c# 代碼執行

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM