C# 呼叫外部exe程式
阿新 • • 發佈:2018-11-06
有時候dll不能引用,那就只能另外做一個exe程式,然後通過呼叫這個程式就可以解決問題,但往往需要在本地生成一箇中間資料。雖然有name一點麻煩,但也挺好用。
這裡就是一個呼叫外部程式的方法。
/// <summary> /// 通過程序呼叫外部程式 /// </summary> /// <param name="exePath"></param> /// <param name="argument"></param> public static void RunExeByProcess(string exePath, string argument) { //開啟新執行緒 System.Diagnostics.Process process = new System.Diagnostics.Process(); //呼叫的exe的名稱 process.StartInfo.FileName = exePath; //傳遞進exe的引數 process.StartInfo.Arguments = argument; process.StartInfo.UseShellExecute = false; //不顯示exe的介面 process.StartInfo.CreateNoWindow = true; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardInput = true; process.Start(); process.StandardInput.AutoFlush = true; process.WaitForExit(); }
如果想獲取呼叫程式返回的的結果,那麼只需要把上面的稍加修改增加返回值即可:
public static string RunExeByProcess(string exePath, string argument) { //開啟新執行緒 System.Diagnostics.Process process = new System.Diagnostics.Process(); //呼叫的exe的名稱 process.StartInfo.FileName = exePath; //傳遞進exe的引數 process.StartInfo.Arguments = argument; process.StartInfo.UseShellExecute = false; //不顯示exe的介面 process.StartInfo.CreateNoWindow = true; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardInput = true; process.Start(); process.StandardInput.AutoFlush = true; string result = null; while (!process.StandardOutput.EndOfStream) { result += process.StandardOutput.ReadLine() + Environment.NewLine; } process.WaitForExit(); return result; }