标签:style blog http io color ar os for sp
/// <summary> /// 服务调用控制 /// </summary> public class WinServiceController { /// <summary> /// 服务开始启用 /// </summary> /// <typeparam name="T">服务调用的类型</typeparam> /// <param name="ServiceName">服务的名称</param> /// <param name="args">应用程序启动传入的参数</param> public static void State<T>(string ServiceName, string[] args) where T : ServiceBase, IServiceController, new() { string key0 = AppDomain.CurrentDomain.FriendlyName; if (args.Length > 0) { string str = args[0].ToLower(); try { if (str == "-install" || str == "-i") { #region //安装本服务 if (null == ServiceIsExisted(ServiceName)) {//如果没有安装,则安装 string key = AppDomain.CurrentDomain.BaseDirectory + key0; ManagedInstallerClass.InstallHelper(new string[] { key }); ServiceController c = new ServiceController(key0.Substring(0, key0.Length - 4)); c.Start(); } else { Log.Write("服务已经安装!无需再安装!"); } #endregion } else if (str == "-uninstall" || str == "-u") { #region //卸载本服务 ServiceController sc = ServiceIsExisted(ServiceName); if (null != sc) {//如果已经安装,则卸载本服务 if (sc.Status != ServiceControllerStatus.Stopped) { sc.Stop();//停止服务 sc.WaitForStatus(ServiceControllerStatus.Stopped);//等待服务完全停止;真方便的函数~ } string key = AppDomain.CurrentDomain.BaseDirectory + AppDomain.CurrentDomain.FriendlyName; ManagedInstallerClass.InstallHelper(new string[] { "/u", key }); } else { Log.Write("服务未安装!不能卸载不存在的服务!"); } #endregion } else if (str == "-start" || str == "-s") { #region //将本服务当做一个应用程序直接运行 Log.Write("消息服务启动开始"); T msm = null; try { msm = new T(); msm.Start(); } catch (Exception msg) { if (null != msm) { msm.Stop(); } } #endregion } } catch (Exception msg) { Log.Write(msg.Message + msg.StackTrace); Log.Write("消息服务异常结束"); } } else { #region //启动本服务 try { ServiceBase.Run(new T()); } catch (Exception msg) { Log.Write(msg.Message + msg.StackTrace); Log.Write("消息服务异常结束"); } #endregion } } /// <summary> /// 检查指定的服务是否存在。 /// </summary> /// <param name="serviceName">要查找的服务名字</param> /// <returns>如果存在则返回真</returns> private static ServiceController ServiceIsExisted(string svcName) { ServiceController[] services = ServiceController.GetServices(); foreach (ServiceController s in services) { if (s.ServiceName == svcName) { return s; } } return null; } }
调用:
在windows服务应用程序中的Program文件
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
public static void Main(string[] args)
{
WinServiceController.State<Service1>("windows服务应用程序exe名称", args);
}
}
标签:style blog http io color ar os for sp
原文地址:http://www.cnblogs.com/zfanlong1314/p/4077620.html