private string excuteCmd(string strCMD)
{
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false;//是否使用操作系统shell启动
p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
p.StartInfo.RedirectStandardError = true;//重定向标准错误输出
//这里根据需要安装服务的框架版本不同,路径也不同,我的是.net3.5的
p.StartInfo.WorkingDirectory = @"C:\Windows\Microsoft.NET\Framework\v2.0.50727";
//p.StartInfo.CreateNoWindow = true;
//p.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
p.Start();//启动程序
p.StandardInput.WriteLine(strCMD);
p.StandardInput.AutoFlush = true;
p.StandardInput.WriteLine(" exit");
p.StandardInput.AutoFlush = true;
//获取cmd窗口的输出信息
string output = p.StandardOutput.ReadToEnd();
//等待程序执行完退出进程
p.WaitForExit();
p.Close();
return output;
}
private string excuteCmd(string strCMD)
{
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false;//是否使用操作系统shell启动
p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
p.StartInfo.RedirectStandardError = true;//重定向标准错误输出
//这里根据需要安装服务的框架版本不同,路径也不同,我的是.net3.5的
p.StartInfo.WorkingDirectory = @"C:\Windows\Microsoft.NET\Framework\v2.0.50727";
//p.StartInfo.CreateNoWindow = true;
//p.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
p.Start();//启动程序
p.StandardInput.WriteLine(strCMD);
p.StandardInput.AutoFlush = true;
p.StandardInput.WriteLine(" exit");
p.StandardInput.AutoFlush = true;
//获取cmd窗口的输出信息
string output = p.StandardOutput.ReadToEnd();
//等待程序执行完退出进程
p.WaitForExit();
p.Close();
return output;
}
在给个启动服务的代码:
private void btn_startService_Click(object sender, EventArgs e)
{
if (!IsServerExists(serviceName))
{
MessageBox.Show("未找到配置文件写的服务:" + serviceName);
return;
}
bool isStarted = false;
ServiceController star_service = new ServiceController(serviceName);
if (star_service.Status != ServiceControllerStatus.Running &&
star_service.Status != ServiceControllerStatus.StartPending)
{
star_service.Start();
//这里是看80s内,服务是否启动完毕
for (int i = 0; i < 80; i++)
{
star_service.Refresh();
System.Threading.Thread.Sleep(1000);
if (star_service.Status == ServiceControllerStatus.Running)
{
isStarted = true;
break;
}
if (i == 79)
{
isStarted = false;
}
}
}
else
{
MessageBox.Show("服务已经启动或被暂停");
return;
}
if (isStarted)
{
MessageBox.Show("服务启动完成!");
}
else
{
MessageBox.Show("服务未在80秒内启动起来,请到服务里去手动启动");
}
}
string strCMD = @"InstallUtil.exe " + txt_filePath.Text;
string output = excuteCmd(strCMD);
代码下载
winform——windows 服务的安装 卸载 启动 停止
原文:https://www.cnblogs.com/HelloQLQ/p/13936982.html