准备工作
Nginx下载
http://nginx.org/en/download.html
下载后放在项目的根目录下
文件夹名设置为nginx
把配置中的默认监听的端口号改为10078
复制Nginx到目标目录
项目->属性->生成事件->生成前事件命令行
添加如下
复制目录
1 2
| taskkill /f /t /im nginx.exe xcopy /Y /i /e $(ProjectDir)\nginx $(TargetDir)\nginx
|
注意
nginx目录下的temp目录不要删除,删除后会导致运行时无法创建该目录而启动Nginx报错
nginx目录中不能包含中文字符串,即软件的安装目录不要设为中文
nginx目录中可以包含空格
CMD中打开关闭
在CMD中打开
1 2
| cd nginxpath .\nginx.exe
|
使用CMD结束
1
| taskkill /f /t /im nginx.exe
|
C#中运行和关闭nginx
打开notepad
我们一般调用外部程序的方法
1 2 3
| Process p = Process.Start("notepad.exe");
p.WaitForExit();
|
运行nginx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| private static void Startnginx() { string basePath = AppDomain.CurrentDomain.BaseDirectory; string nginxPath = System.IO.Path.Combine(basePath, "nginx");
Process mps = new Process(); ProcessStartInfo mpsi = new ProcessStartInfo("nginx.exe"); mpsi.WorkingDirectory = nginxPath; mpsi.UseShellExecute = true; mpsi.RedirectStandardInput = false; mpsi.RedirectStandardOutput = false; mpsi.CreateNoWindow = true; mpsi.WindowStyle = ProcessWindowStyle.Hidden; mps.StartInfo = mpsi; mps.Start(); }
|
说明
调用nginx一定要注意以下参数的设置,否则不生效
mpsi.WorkingDirectory = nginxPath;
mpsi.UseShellExecute = true;
mpsi.RedirectStandardInput = false;
mpsi.RedirectStandardOutput = false;
结束nginx
使用C#结束
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| private static void Stopnginx() { Process[] processes = Process.GetProcessesByName("nginx"); foreach (Process p in processes) { string basePath = AppDomain.CurrentDomain.BaseDirectory; string nginxPath = System.IO.Path.Combine(basePath, "nginx", "nginx.exe"); if (nginxPath == p.MainModule.FileName) { p.Kill(); p.Close(); } } }
|
注意
进程名称不要写成nginx.exe,会找不到nginx进程。
本来我还尝试了用进程对象来结束,但是不行,因为nginx启动会产生多个进程,单独结束掉一个是不行的!