需要操作的服务是一个已经生成好的Windows服务,具体如何创建一个服务,在Windows服务中有详细的介绍。
需要添加的头文件:
using System;
using System.Configuration.Install;
using System.Collections;
using System.Collections.Specialized;
这是一个新建的对象,根据使用需求决定是否使用。
IDictionary stateSaver = new Hashtable();
将这些服务操作封装到一个类中,这样使用起来就会方便很多。using System;
using System.Collections.Generic;
using System.Configuration.Install;
using System.Linq;
using System.ServiceProcess;
using System.Text;
namespace WindowsService1
{
public class ServiceClass1 : Interface1
{
/// <summary>
/// 安装服务
/// </summary>
/// <param name="stateSaver">可以设置为null</param>
/// <param name="filepath">待安装服务的路径</param>
public void InstallService(System.Collections.IDictionary stateSaver, string filepath)
{
try
{
System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController("Service121");
if (!ServiceIsExisted("Service121"))
{
//Install Service
AssemblyInstaller myAssemblyInstaller = new AssemblyInstaller();
myAssemblyInstaller.UseNewContext = true;
myAssemblyInstaller.Path = filepath;
myAssemblyInstaller.Install(stateSaver);
myAssemblyInstaller.Commit(stateSaver);
myAssemblyInstaller.Dispose();
//--Start Service
service.Start();
}
else
{
if (service.Status != System.ServiceProcess.ServiceControllerStatus.Running && service.Status != System.ServiceProcess.ServiceControllerStatus.StartPending)
{
service.Start();
}
}
}
catch (Exception ex)
{
throw new Exception("installServiceError/n" + ex.Message);
// Console.WriteLine(ex.Message);
}
}
/// <summary>
/// 卸载服务
/// </summary>
/// <param name="filepath">服务存在的路径,与安装的路径一样</param>
public void UnInstallService(string filepath)
{
try
{
if (ServiceIsExisted("Service121"))
{
//UnInstall Service
AssemblyInstaller myAssemblyInstaller = new AssemblyInstaller();
myAssemblyInstaller.UseNewContext = true;
myAssemblyInstaller.Path = filepath;
myAssemblyInstaller.Uninstall(null);
myAssemblyInstaller.Dispose();
}
}
catch (Exception ex)
{
throw new Exception("unInstallServiceError/n" + ex.Message);
}
}
/// <summary>
/// 判断服务是否已经安装
/// </summary>
/// <param name="serviceName">服务的名称</param>
/// <returns></returns>
public bool ServiceIsExisted(string serviceName)
{
ServiceController[] services = ServiceController.GetServices();
foreach (ServiceController s in services)
{
if (s.ServiceName == serviceName)
{
return true;
}
}
return false;
}
/// <summary>
/// 开启服务
/// </summary>
/// <param name="serviceName">服务的名称</param>
public void StartService(string serviceName)
{
if (ServiceIsExisted(serviceName))
{
System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(serviceName);
if (service.Status != System.ServiceProcess.ServiceControllerStatus.Running && service.Status != System.ServiceProcess.ServiceControllerStatus.StartPending)
{
service.Start();
for (int i = 0; i < 60; i++)
{
service.Refresh();
System.Threading.Thread.Sleep(1000);
if (service.Status == System.ServiceProcess.ServiceControllerStatus.Running)
{
break;
}
if (i == 59)
{
throw new Exception("startService");
//throw new Exception(startServiceError.Replace("$s$", serviceName));
}
}
}
}
}
/// <summary>
/// 关闭服务
/// </summary>
/// <param name="serviceName">服务的名称</param>
public void StopService(string serviceName)
{
if (ServiceIsExisted(serviceName))
{
System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(serviceName);
if (service.Status == System.ServiceProcess.ServiceControllerStatus.Running)
{
service.Stop();
for (int i = 0; i < 60; i++)
{
service.Refresh();
System.Threading.Thread.Sleep(1000);
if (service.Status == System.ServiceProcess.ServiceControllerStatus.Stopped)
{
break;
}
if (i == 59)
{
throw new Exception("StopService");
// throw new Exception( stopServiceError.Replace("$s$", serviceName));
}
}
}
}
}
}
}
安装服务也可以使用下面的方法:
/// <summary>
/// 安装服务
/// </summary>
/// <param name="p_Path">指定服务文件路径</param>
/// <param name="p_ServiceName">返回安装完成后的服务名</param>
/// <returns>安装信息 正确安装返回""</returns>
public static string InsertService(string p_Path, ref string p_ServiceName)
{
if (!File.Exists(p_Path)) return "文件不存在!";
p_ServiceName = "";
FileInfo _InsertFile = new FileInfo(p_Path);
IDictionary _SavedState = new Hashtable();
try
{
//加载一个程序集,并运行其中的所有安装程序。
AssemblyInstaller _AssemblyInstaller = new AssemblyInstaller(p_Path, new string[] { "/LogFile=" + _InsertFile.DirectoryName + "//" + _InsertFile.Name.Substring(0, _InsertFile.Name.Length - _InsertFile.Extension.Length) + ".log" });
_AssemblyInstaller.UseNewContext = true;
_AssemblyInstaller.Install(_SavedState);
_AssemblyInstaller.Commit(_SavedState);
Type[] _TypeList = _AssemblyInstaller.Assembly.GetTypes();//获取安装程序集类型集合
for (int i = 0; i != _TypeList.Length; i++)
{
if (_TypeList[i].BaseType.FullName == "System.Configuration.Install.Installer")
{
//找到System.Configuration.Install.Installer 类型
object _InsertObject = System.Activator.CreateInstance(_TypeList[i]);//创建类型实列
FieldInfo[] _FieldList = _TypeList[i].GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
for (int z = 0; z != _FieldList.Length; z++)
{
if (_FieldList[z].FieldType.FullName == "System.ServiceProcess.ServiceInstaller")
{
object _ServiceInsert = _FieldList[z].GetValue(_InsertObject);
if (_ServiceInsert != null)
{
p_ServiceName = ((ServiceInstaller)_ServiceInsert).ServiceName;
return "";
}
}
}
}
}
return "";
}
catch (Exception ex)
{
return ex.Message;
}
}
启动服务:
/// <summary>
/// 启动服务
/// </summary>
/// <param name="serviceName"></param>
/// <returns></returns>
public static bool ServiceStart(string serviceName)
{
try
{
ServiceController service = new ServiceController(serviceName);
if (service.Status == ServiceControllerStatus.Running)
{
return true;
}
else
{
TimeSpan timeout = TimeSpan.FromMilliseconds(1000 * 10);
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running, timeout);
}
}
catch
{
return false;
}
return true;
}
停止服务:
/// <summary>
/// 停止服务
/// </summary>
/// <param name="serviseName"></param>
/// <returns></returns>
public static bool ServiceStop(string serviseName)
{
try
{
ServiceController service = new ServiceController(serviseName);
if (service.Status == ServiceControllerStatus.Stopped)
{
return true;
}
else
{
TimeSpan timeout = TimeSpan.FromMilliseconds(1000 * 10);
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Running, timeout);
}
}
catch
{
return false;
}
return true;
}
/// <summary>
/// 修改服务的启动项 2为自动,3为手动
/// </summary>
/// <param name="startType"></param>
/// <param name="serviceName"></param>
/// <returns></returns>
public static bool ChangeServiceStartType(int startType, string serviceName)
{
try
{
RegistryKey regist = Registry.LocalMachine;
RegistryKey sysReg = regist.OpenSubKey("SYSTEM");
RegistryKey currentControlSet = sysReg.OpenSubKey("CurrentControlSet");
RegistryKey services = currentControlSet.OpenSubKey("Services");
RegistryKey servicesName = services.OpenSubKey(serviceName, true);
servicesName.SetValue("Start", startType);
}
catch (Exception ex)
{
return false;
}
return true;
}
获取服务启动类型
/// <summary>
/// 获取服务启动类型 2为自动 3为手动 4 为禁用
/// </summary>
/// <param name="serviceName"></param>
/// <returns></returns>
public static string GetServiceStartType(string serviceName)
{
try
{
RegistryKey regist = Registry.LocalMachine;
RegistryKey sysReg = regist.OpenSubKey("SYSTEM");
RegistryKey currentControlSet = sysReg.OpenSubKey("CurrentControlSet");
RegistryKey services = currentControlSet.OpenSubKey("Services");
RegistryKey servicesName = services.OpenSubKey(serviceName, true);
return servicesName.GetValue("Start").ToString();
}
catch (Exception ex)
{
return string.Empty;
}
}
验证服务是否启动 服务是否存在
/// <summary>
/// 验证服务是否启动
/// </summary>
/// <returns></returns>
public static bool ServiceIsRunning(string serviceName)
{
ServiceController service = new ServiceController(serviceName);
if (service.Status == ServiceControllerStatus.Running)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 服务是否存在
/// </summary>
/// <param name="serviceName"></param>
/// <returns></returns>
public static bool ServiceExist(string serviceName)
{
try
{
string m_ServiceName = serviceName;
ServiceController[] services = ServiceController.GetServices();
foreach (ServiceController s in services)
{
if (s.ServiceName.ToLower() == m_ServiceName.ToLower())
{
return true;
}
}
return false;
}
catch (Exception ex)
{
return false;
}
}