//[DllImport("advapi32.dll", SetLastError=true, CharSet=CharSet.Auto)] //[return: MarshalAs(UnmanagedType.Bool)] //public static extern bool ChangeServiceConfig2(IntPtr hService, int dwInfoLevel, IntPtr lpInfo); public static void Install(WindowsServiceDescription description, CancellationToken token = default(CancellationToken)) { var scm = OpenSCManager(ScmAccessRights.AllAccess); try { var service = OpenService(scm, description.Name, ServiceAccessRights.AllAccess); if (service != IntPtr.Zero) { throw new ApplicationException($"Service '{description.Name}' already exists!"); } service = CreateService(scm, description.Name, description.DisplayName, ServiceAccessRights.AllAccess, SERVICE_WIN32_OWN_PROCESS, description.StartMode, ServiceError.Normal, description.Filename, null, IntPtr.Zero, null, description.Username, description.Password); if (service == IntPtr.Zero) { throw new ApplicationException("Failed to install service."); } CloseServiceHandle(service); //try { // await StartServiceAsync(service, token); //} //finally { // CloseServiceHandle(service); //} } finally { CloseServiceHandle(scm); } }
public static void Configure(WindowsServiceDescription description) { var scm = OpenSCManager(ScmAccessRights.Connect); try { var service = OpenService(scm, description.Name, ServiceAccessRights.QueryConfig | ServiceAccessRights.ChangeConfig); if (service == IntPtr.Zero) { throw new ApplicationException("Could not open service."); } try { var result = ChangeServiceConfig( service, SERVICE_NO_CHANGE, (uint)description.StartMode, SERVICE_NO_CHANGE, description.Filename, null, IntPtr.Zero, null, description.Username, description.Password, description.DisplayName); if (!result) { var nError = Marshal.GetLastWin32Error(); var win32Exception = new Win32Exception(nError); throw new ExternalException($"Could not change service start type: {win32Exception.Message}"); } } finally { CloseServiceHandle(service); } } finally { CloseServiceHandle(scm); } }