/// <summary> /// 安装服务 /// </summary> /// <param name="serviceName">服务名</param> /// <param name="displayName">友好名称</param> /// <param name="binaryFilePath">映像文件路径,可带参数</param> /// <param name="description">服务描述</param> /// <param name="startType">启动类型</param> /// <param name="account">启动账户</param> /// <param name="dependencies">依赖服务</param> public static void Install(string serviceName, string displayName, string binaryFilePath, string description, ServiceStartType startType, ServiceAccount account = ServiceAccount.LocalSystem, string[] dependencies = null) { IntPtr scm = OpenSCManager(); IntPtr service = IntPtr.Zero; try { service = Win32Class.CreateService(scm, serviceName, displayName, Win32Class.SERVICE_ALL_ACCESS, Win32Class.SERVICE_WIN32_OWN_PROCESS, startType, Win32Class.SERVICE_ERROR_NORMAL, binaryFilePath, null, IntPtr.Zero, ProcessDependencies(dependencies), GetServiceAccountName(account), null); if (service == IntPtr.Zero) { if (Marshal.GetLastWin32Error() == 0x431)//ERROR_SERVICE_EXISTS { throw new ApplicationException("服务已存在!"); } throw new ApplicationException("服务安装失败!"); } //设置服务描述 Win32Class.SERVICE_DESCRIPTION sd = new Win32Class.SERVICE_DESCRIPTION(); try { sd.description = Marshal.StringToHGlobalUni(description); Win32Class.ChangeServiceConfig2(service, 1, ref sd); } finally { Marshal.FreeHGlobal(sd.description); //释放 } } finally { if (service != IntPtr.Zero) { Win32Class.CloseServiceHandle(service); } Win32Class.CloseServiceHandle(scm); } }
/// <summary> /// 安装服务 /// </summary> /// <param name="serviceName">服务名</param> /// <param name="displayName">友好名称</param> /// <param name="description">服务描述</param> /// <param name="binaryFilePath">映像文件路径,可带参数</param> /// <param name="startType">启动类型</param> /// <param name="account">启动账户</param> /// <param name="dependencies">依赖服务</param> public static void Install(string serviceName, string displayName, string description, string binaryFilePath, ServiceStartType startType, ServiceAccount account = ServiceAccount.LocalSystem, string[] dependencies = null) { IntPtr scm = OpenSCManager(); IntPtr service = IntPtr.Zero; try { service = Win32Class.CreateService(scm, serviceName, displayName, Win32Class.SERVICE_ALL_ACCESS, Win32Class.SERVICE_WIN32_OWN_PROCESS, startType, Win32Class.SERVICE_ERROR_NORMAL, binaryFilePath, null, IntPtr.Zero, ProcessDependencies(dependencies), GetServiceAccountName(account), null); if (service == IntPtr.Zero) { if (Marshal.GetLastWin32Error() == 0x431)//ERROR_SERVICE_EXISTS { throw new ApplicationException("服务已存在!"); } throw new ApplicationException("服务安装失败!"); } //设置服务描述 Win32Class.SERVICE_DESCRIPTION sd = new Win32Class.SERVICE_DESCRIPTION(); try { sd.description = Marshal.StringToHGlobalUni(description); Win32Class.ChangeServiceConfig2(service, 1, ref sd); } finally { Marshal.FreeHGlobal(sd.description); //释放 } } finally { if (service != IntPtr.Zero) { Win32Class.CloseServiceHandle(service); } Win32Class.CloseServiceHandle(scm); } }