本文介绍了从Windows C#app启动服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好, 我开发了一个C#windows应用程序,通过它我可以在Windows 7中安装服务但无法运行该服务。请帮忙。
解决方案这里有一些方便的代码: public string 开始( string serviceName) { 使用(ServiceController serviceController = new ServiceController(serviceName)) { try { serviceController.Start(); serviceController.WaitForStatus(ServiceControllerStatus.Running,TimeSpan.FromSeconds( 30 )); return + ok; } catch (例外情况) { return - + ex.Message; } } }
这就是你想要的吗?
试试下面的代码希望它能帮到你 public void StartService( string ServiceName) { // 使用System.ServiceProcess添加命名空间;使用ServiceController类 ServiceController myService = new ServiceController(); myService.ServiceName = ServiceName; string svcStatus = myService.Status.ToString(); if (svcStatus == 已停止 ) { myService.Start(); string svcStatusWas = ; while (svcStatus!= 正在运行 ) { svcStatusWas = svcStatus; myService.Refresh(); svcStatus = myService.Status.ToString(); } // 服务已开始 } else { // 如果服务处于任何其他状态,请停止服务 myService.Stop(); while (svcStatus!= 已停止 ) { myService.Refresh(); svcStatus = myService.Status.ToString(); } myService.Start(); string svcStatusWas = ; while (svcStatus!= 正在运行 ) { svcStatusWas = svcStatus; myService.Refresh(); svcStatus = myService.Status.ToString(); } // 服务已开始 } }
Hi All, I am developed a C# windows application through which I am able to install a service in windows 7 but not able to run the service. Please help.
解决方案 Here's a bit of code I have handy: public string Start(string serviceName) { using (ServiceController serviceController = new ServiceController(serviceName)) { try { serviceController.Start(); serviceController.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(30)); return "+ ok"; } catch (Exception ex) { return "- " + ex.Message; } } }Is that what you want?
Try out the below code hope it will help you out public void StartService(string ServiceName) { //Add namespace using System.ServiceProcess; for using ServiceController class ServiceController myService = new ServiceController(); myService.ServiceName =ServiceName; string svcStatus = myService.Status.ToString(); if (svcStatus == "Stopped") { myService.Start(); string svcStatusWas = ""; while (svcStatus != "Running") { svcStatusWas = svcStatus; myService.Refresh(); svcStatus = myService.Status.ToString(); } //Service Started } else { // STOP the service if it is in any other state myService.Stop(); while (svcStatus != "Stopped") { myService.Refresh(); svcStatus = myService.Status.ToString(); } myService.Start(); string svcStatusWas = ""; while (svcStatus != "Running") { svcStatusWas = svcStatus; myService.Refresh(); svcStatus = myService.Status.ToString(); } //Service Started } }更多推荐
从Windows C#app启动服务
发布评论