通过C#的Process启动Nginx(C#代码实现通过操作命令行启动应用程序)


背景:因为一个特殊的需求,需要在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起来了~


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM