2017-02-07 24 views
1

我目前正試圖「轉換」我寫給C#的bash腳本。 這個腳本在shell啓動程序,然後在這個shell執行一些命令,看起來與此類似:執行帶有參數和來自C#的多個命令.exe

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「並在啓動的進程中執行命令。

+0

我發現用cmd.exe執行多個命令最多是尷尬的。如果您將命令寫入.cmd文件並執行該命令,則更好。您的.cmd文件中將具有「正常」批處理語法。 – Clay

回答

1

我不知道如果我沒有理解你的問題,但你可以在你的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#代碼執行

+0

你能告訴我如何在批處理腳本中的bash腳本中添加一個像「<< EOF ......」這樣的文檔,或者做出一些結果相同的東西嗎? – Martin

+0

我不明白你的問題,你是什麼意思,「在這裏添加一個文件」和「在我的bash腳本中的批處理腳本或製作」 –

+0

不再重要。我想出瞭如何去做。 「鍵入sometext.txt | myexe.exe -s」幫助。 Thx爲您的答案! – Martin