首先将windows service发布到web的bin目录
public class HomeController : Controller { string sName = "MyService1"; public ActionResult Index() { try { ServiceController sc = new ServiceController(sName); ViewBag.Statu = sc.Status.ToString(); } catch (Exception e) { ViewBag.Statu = e.Message; } return View(); } public ActionResult StartService() { try { ServiceController sc = new ServiceController(sName); sc.Refresh(); if (sc.Status == ServiceControllerStatus.Stopped) { sc.Start(); sc.WaitForStatus(ServiceControllerStatus.Running); sc.Close(); } } catch (Exception e) { ViewBag.Statu = e.Message; } return null; } public ActionResult StopService() { try { ServiceController sc = new ServiceController(sName); if (sc.Status == ServiceControllerStatus.Running) { sc.Stop(); sc.WaitForStatus(ServiceControllerStatus.Stopped); sc.Close(); } } catch (Exception e) { throw e; } return null; } public ActionResult ReStartService() { ServiceController sc = new ServiceController(sName); if (sc != null) { if (sc.Status == ServiceControllerStatus.Stopped) { sc.Start(); sc.WaitForStatus(ServiceControllerStatus.Running); } else if (sc.Status == ServiceControllerStatus.Running) { sc.Stop(); sc.WaitForStatus(ServiceControllerStatus.Stopped); sc.Start(); sc.WaitForStatus(ServiceControllerStatus.Running); } sc.Close(); } return null; } public ActionResult InstallService() { IDictionary stateSaver=new Hashtable(); string[] cmdLine = { }; ServiceController sc = new ServiceController(sName); if(!ServiceIsExisted(sName)) { try { AssemblyInstaller installer = new AssemblyInstaller(); installer.Path = Server.MapPath("/bin/WindowsServiceTest.exe"); installer.UseNewContext = true; installer.Install(null); installer.Commit(null); installer.Dispose(); } catch (Exception e) { throw e; } } sc.Close(); //WindowsServiceTest.vshost.exe return null; } public ActionResult UninstallService() { ServiceController sc = new ServiceController(sName); if (ServiceIsExisted(sName)) { try { AssemblyInstaller installer = new AssemblyInstaller(); installer.UseNewContext = true; installer.Path = Server.MapPath("/bin/WindowsServiceTest.exe"); installer.Uninstall(null); } catch (Exception e) { throw e; } } sc.Close(); return null; } private bool ServiceIsExisted(string sName) { ServiceController[] services = ServiceController.GetServices(); foreach (ServiceController s in services) { if (s.ServiceName == sName) { return true; } } return false; } }