///
/// 服务调用控制
///
public class WinServiceController
{
///
/// 服务开始启用
///
/// 服务调用的类型
/// 服务的名称
/// 应用程序启动传入的参数
public static void State(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
}
}
///
/// 检查指定的服务是否存在。
///
/// 要查找的服务名字
/// 如果存在则返回真
private static ServiceController ServiceIsExisted(string svcName)
{
ServiceController[] services = ServiceController.GetServices();
foreach (ServiceController s in services)
{
if (s.ServiceName == svcName)
{
return s;
}
}
return null;
}
}