您的位置:首页 > 其它

service controller来安装、卸载、控制服务

2015-11-03 14:12 162 查看
首先将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;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: