背景:因為一個特殊的需求,需要在WPF程序中嵌入Nginx,並能通過WPF啟動停止Nginx服務。直接Process.Strat("nginx.exe",path);無法正常啟動,折騰半天找到的一條方法,記錄分享。
1 private void LaunchNginx() 2 { 3 try 4 { 5 ProcessStartInfo info = new ProcessStartInfo(); 6 info.FileName = "cmd.exe"; 7 info.UseShellExecute = false; 8 info.RedirectStandardInput = true; 9 info.RedirectStandardOutput = true; 10 info.CreateNoWindow = true; 11 Process p = new Process(); 12 p.StartInfo = info; 13 p.Start(); 14 //p.PriorityClass = ProcessPriorityClass.RealTime; 15 string cmdStr = "cd " + System.AppDomain.CurrentDomain.BaseDirectory + "nginx-1.16.0"; 16 cmdStr = cmdStr.Replace("\\", "\\\\"); 17 p.StandardInput.WriteLine(cmdStr); 18 //cmd啟動程序 19 p.StandardInput.WriteLine("nginx.exe"); 20 //Thread.Sleep(2000); 21 p.StandardInput.WriteLine("exit"); 22 } 23 catch (Exception ex) 24 { 25 //throw; 26 Logger.WriteToError(ex, "Nginx服務啟動失敗"); 27 } 28 29 }
如圖Nginx起來了~