Beispiel #1
0
        private static ServiceController CreateService()
        {
            var service = ServiceController.GetServices().FirstOrDefault(con => con.ServiceName == ServiceName);

            if (service != null)
            {
                throw new Exception(string.Format("Service '{0}' already installed", ServiceName));
            }

            _log.DebugFormat("Try to install service '{0}'", ServiceName);

            var parameters = string.Join(" ", _parameters.Select(i => "-" + i.Key + (i.Value != null ? "=" + i.Value : string.Empty)));
            var appPath    = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
            var svcPath    = string.Format("\"{0}\\{1}.exe\" {2}", appPath, _appName, parameters);

            if (!DirectServiceInstaller.InstallService(svcPath, ServiceName, _displayName, Description, true, false))
            {
                throw new Exception("Can't install service. Check user rights for this operation.");
            }

            // проверяем, что сервис установился
            service = ServiceController.GetServices().FirstOrDefault(con => con.ServiceName == ServiceName);
            if (service == null)
            {
                throw new Exception(string.Format("Can't find just installed service '{0}'", ServiceName));
            }

            _log.DebugFormat("Service '{0}' successfully installed", ServiceName);
            return(service);
        }
Beispiel #2
0
        private static void RemoveService()
        {
            var service = ServiceController.GetServices().FirstOrDefault(con => con.ServiceName == ServiceName);

            if (service == null)
            {
                _log.WarnFormat("Can't stop service '{0}'. Service not found", ServiceName);
                return;
            }

            // если работает - останавливаем
            if (service.Status == ServiceControllerStatus.Running)
            {
                service.Stop();
            }

            // удаляем
            _log.InfoFormat(
                DirectServiceInstaller.UnInstallService(ServiceName)
                    ? "Service '{0}' successfully removed"
                    : "Can't remove '{0}' service. Unknown error in ServiceInstaller", ServiceName);
        }