(方法一)返回值為int
fileName為調用的exe路徑,入口參數為para,其中多個參數用空格分開,當D:/DD.exe返回值為int類型時。
Process p = new Process(); string fileName = @"D:/DD.exe"; string para ="aa bb"; ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(fileName, para); p.StartInfo = myProcessStartInfo; p.Start(); while (!p.HasExited) { p.WaitForExit(); } int returnValue = p.ExitCode;
(方法二)返回值位string
返回值為string時,首先在生成DD.exe時主函數main返回值為void,但在主函數要用Write輸出string,通過StandardOutput.ReadToEnd()獲取輸出流(即輸出的字符串)
string fileName = @"D:/DD.exe"; Process p = new Process(); p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.FileName = fileName; p.StartInfo.CreateNoWindow = true; p.StartInfo.Arguments = "aa bb cc";//參數以空格分隔 p.Start(); p.WaitForExit(); string output = p.StandardOutput.ReadToEnd();
p.Dispose();
p.Close();
PS:
1 、在輸入參數 p.StartInfo.Arguments時,由於是以空格分隔,所以,當參數中含有字符串時,會強行分隔。比如我的入口參數需要以下四個參數:“D:\\Demo\\picWorldCup\\worldCup_cy.png” “Canon MG3600 series Printer XPS” “330” “471”,如果我直接寫成如下形式(即直接用空格連接起來)p.StartInfo.Arguments=“D:\\Demo\\picWorldCup\\worldCup_cy.png Canon MG3600 series Printer XPS 330 471顯然是不可以的,此時應該通過轉義字符\"把屬於一個參數的內容包含起來即可,如
p.StartInfo.Arguments = "\"D:\\Demo\\picWorldCup\\worldCup_cy.png\" \"Canon MG3600 series Printer XPS\" 330 471";
2 、如果不想彈窗, 除了設置p.StartInfo.CreateNoWindow = true;外還要p.Close();