public void RestartService() { if (serviceController != null && serviceController.Status == System.ServiceProcess.ServiceControllerStatus.Running) { try { serviceController.Stop(); while (serviceController.Status == System.ServiceProcess.ServiceControllerStatus.Running || serviceController.Status == System.ServiceProcess.ServiceControllerStatus.StopPending) { Application.DoEvents(); } serviceController.Start(); } catch { } } }
private bool bStopWindowsService() { if (!bWindowsServiceInstaled()) { bWindowsServiceInstall(); } if (!bWindowsServiceInstaled()) { return(false); } System.ServiceProcess.ServiceController scSiscoMensagem = scReturnSiscoMensagem(); switch (scSiscoMensagem.Status) { case System.ServiceProcess.ServiceControllerStatus.ContinuePending: case System.ServiceProcess.ServiceControllerStatus.Running: case System.ServiceProcess.ServiceControllerStatus.StartPending: case System.ServiceProcess.ServiceControllerStatus.Paused: case System.ServiceProcess.ServiceControllerStatus.PausePending: try { scSiscoMensagem.Stop(); }catch { return(false); } break; } return(this.State == mdlConstantes.SiscoMensagemState.Stoped); }
protected void ExecutionConfirmed(object sender, EventArgs e) { panelMain.Visible = true; confirmPanel.Visible = false; System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController("EOBProcessing"); try { sc.Stop(); System.Threading.Thread.Sleep(5000); dbProcedures db = new dbProcedures(); System.Data.SqlClient.SqlCommand sqlCmd = new System.Data.SqlClient.SqlCommand("usp_AddOneTimeRunSchedule", new db().SqlConnection); sqlCmd.CommandType = System.Data.CommandType.StoredProcedure; sqlCmd.ExecuteNonQuery(); db.Close(); sc.Start(); lblMessage.Text = "EOB System manual execution started."; } catch (Exception e1) { lblMessage.Text = "Failed to manually start EOB System service." + e1.Message(); } }
private void llblServiceState_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { try { Application.DoEvents(); this.Cursor = Cursors.WaitCursor; System.ServiceProcess.ServiceController qsvrc = new System.ServiceProcess.ServiceController("QuickMon 5 Service"); lblServiceState.Text = qsvrc.Status.ToString(); if (llblServiceState.Text == "Start" && qsvrc.Status == System.ServiceProcess.ServiceControllerStatus.Stopped) { qsvrc.Start(); qsvrc.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Running); } else if (llblServiceState.Text == "Stop" && qsvrc.Status == System.ServiceProcess.ServiceControllerStatus.Running) { qsvrc.Stop(); qsvrc.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Stopped); } lblServiceState.Text = qsvrc.Status.ToString(); CheckQuickMonServiceInstalled(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } this.Cursor = Cursors.Default; }
public static void Kill(bool restart) { HandleClosed(); #if !MONO if (!m_Service) { if (restart) { Process.Start(ExePath, Arguments); } m_Process.Kill(); } else { if (restart) { m_Process.Kill(); } else { System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController("RunUO Service"); if (service.Status == System.ServiceProcess.ServiceControllerStatus.Running) { service.Stop(); } } } #else if (restart && !m_Service) { Process.Start(ExePath, Arguments); } m_Process.Kill(); #endif }
/// <summary> /// 启动windows服务,只要服务当前状态不是已停止,就停止它,并等待至停止成功,返回true。停止失败,抛出Exception /// </summary> /// <param name="sServiceName"></param> /// <returns></returns> public bool StopWindowService(string sServiceName) { try { if (String.IsNullOrEmpty(sServiceName)) { return(false); } System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController(sServiceName); if (sc != null) { if (sc.Status != System.ServiceProcess.ServiceControllerStatus.Stopped) { sc.Stop(); sc.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Stopped); return(true); } return(true); } } catch (Exception e) { Tools.WriteLog(e.ToString()); throw e; } //process not found, return false return(false); }
private void mi_MailServiceStop_Click(object sender, System.EventArgs e) { serviceController = new System.ServiceProcess.ServiceController("SMTPSVC"); if (serviceController.Status == System.ServiceProcess.ServiceControllerStatus.Running) { try { // Start the service, and wait until its status is "Running". serviceController.Stop(); serviceController.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Stopped); // Display the current service status. MessageBox.Show("Mail Service is Stopped successfully...", "Service Operation Notification", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (InvalidOperationException) { MessageBox.Show("Unable to Stop Mail Service ...", "Service Operation Notification", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { MessageBox.Show("Mail Service is alrerady Stopped ...", "Service Operation Notification", MessageBoxButtons.OK, MessageBoxIcon.Information); } }
/// <summary> /// 停止系统服务 /// </summary> /// <param name="sc"></param> public static void StopService(System.ServiceProcess.ServiceController sc) { if (sc.CanStop) { sc.Stop(); sc.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Stopped); } }
private void serviceInstaller1_BeforeUninstall(object sender, InstallEventArgs e) { System.ServiceProcess.ServiceController svr = new System.ServiceProcess.ServiceController(this.serviceInstaller1.ServiceName); if (svr != null) { svr.Stop(); } }
public static void ScheduleService() { try { Schedular = new Timer(new TimerCallback(SchedularCallback)); string mode = ConfigurationManager.AppSettings["Mode"].ToUpper(); log.Info("Recon Service Mode: " + mode); //Set the Default Time. DateTime scheduledTime = DateTime.MinValue; if (mode == "DAILY") { //Get the Scheduled Time from AppSettings. scheduledTime = DateTime.Parse(System.Configuration.ConfigurationManager.AppSettings["ScheduledTime"]); if (DateTime.Now > scheduledTime) { //If Scheduled Time is passed set Schedule for the next day. scheduledTime = scheduledTime.AddDays(1); } } if (mode.ToUpper() == "INTERVAL") { //Get the Interval in Minutes from AppSettings. int intervalMinutes = Convert.ToInt32(ConfigurationManager.AppSettings["IntervalMinutes"]); //Set the Scheduled Time by adding the Interval to Current Time. scheduledTime = DateTime.Now.AddMinutes(intervalMinutes); if (DateTime.Now > scheduledTime) { //If Scheduled Time is passed set Schedule for the next Interval. scheduledTime = scheduledTime.AddMinutes(intervalMinutes); } } TimeSpan timeSpan = scheduledTime.Subtract(DateTime.Now); string schedule = string.Format("{0} day(s) {1} hour(s) {2} minute(s) {3} seconds(s)", timeSpan.Days, timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds); log.Info("Recon Service scheduled to run after: " + schedule); //Get the difference in Minutes between the Scheduled and Current Time. int dueTime = Convert.ToInt32(timeSpan.TotalMilliseconds); //Change the Timer's Due Time. Schedular.Change(dueTime, Timeout.Infinite); } catch (Exception ex) { log.Error("Recon Service Error on: {0} " + ex.Message + ex.StackTrace); //Stop the Windows Service. using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController("ReconService")) { serviceController.Stop(); } } }
static void OnProcessExit(object sender, EventArgs e) { try { var service = new System.ServiceProcess.ServiceController("PCManagerService"); service.Stop(); service.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Stopped); } catch { } }
public static void StopService(string serviceName) { var controller = new System.ServiceProcess.ServiceController(serviceName); if (controller.CanStop) { controller.Stop(); } }
private void cmdStop_Click(object sender, RoutedEventArgs e) { try { System.ServiceProcess.ServiceController dienst = new System.ServiceProcess.ServiceController(StaticServiceConfig.MyServiceName); dienst.Stop(); } catch (Exception) { } }
private void cmdServiceStop_Click(object sender, EventArgs e) { try { System.ServiceProcess.ServiceController dienst = new System.ServiceProcess.ServiceController(ProjectInstaller.ServiceName); dienst.Stop(); } catch (Exception) { } }
public void StopService(string strServiceName) { System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController(); //DataSendingService sc.ServiceName = strServiceName; if (sc.Status == System.ServiceProcess.ServiceControllerStatus.Running) { sc.Stop(); } }
private void button2_Click(object sender, EventArgs e) { System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController(); sc.ServiceName = "MSSQLSERVER"; if (!sc.Status.Equals(System.ServiceProcess.ServiceControllerStatus.Stopped)) { sc.Stop(); MessageBox.Show("SQL数据库服务已经关闭!", "提示信息"); } }
private void ProjectInstaller_BeforeUninstall(object sender, InstallEventArgs e) { //アンインストール直前自動停止 System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController(); sc.ServiceName = "log4netRemotingService"; if (sc.CanStop) { sc.Stop(); } }
void ProjectInstaller_BeforeInstall(object sender, InstallEventArgs e) { try { System.ServiceProcess.ServiceController controller = new System.ServiceProcess.ServiceController(intrusionDetectionServiceInstaller.DisplayName); if (controller != null && controller.Status == System.ServiceProcess.ServiceControllerStatus.Running) { controller.Stop(); } } catch { } }
void ProjectInstaller_BeforeUninstall(object sender, InstallEventArgs e) { try { System.ServiceProcess.ServiceController controller = new System.ServiceProcess.ServiceController(intrusionDetectionServiceInstaller.DisplayName); if (controller != null && controller.Status == System.ServiceProcess.ServiceControllerStatus.Running) { controller.Stop(); } } catch (Exception ex) { System.Diagnostics.EventLog.WriteEntry("Cyberarms Intrusion Detection Installer", "Error: " + ex.Message); } }
/// <summary> /// 停止 Windows 服务 /// </summary> /// <param name="serviceName">服务名称。</param> public static void StopService(string serviceName) { if (IsServiceExisted(serviceName)) { System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(serviceName); if (service.Status != System.ServiceProcess.ServiceControllerStatus.StopPending && service.Status != System.ServiceProcess.ServiceControllerStatus.Stopped) { service.Stop(); } service.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Stopped, System.TimeSpan.FromSeconds(60)); } }
public void ScheduleService() { try { Schedular = new Timer(new TimerCallback(SchedularCallback)); string mode = ConfigurationManager.AppSettings["Mode"].ToUpper(); //Set the Default Time. DateTime scheduledTime = DateTime.MinValue; if (mode == "DAILY") { //Get the Scheduled Time from AppSettings. scheduledTime = DateTime.Parse(System.Configuration.ConfigurationManager.AppSettings["ScheduledTime"]); if (DateTime.Now > scheduledTime) { //If Scheduled Time is passed set Schedule for the next day. scheduledTime = scheduledTime.AddDays(1); } } if (mode.ToUpper() == "INTERVAL") { //Get the Interval in Minutes from AppSettings. int intervalMinutes = Convert.ToInt32(ConfigurationManager.AppSettings["IntervalMinutes"]); //Set the Scheduled Time by adding the Interval to Current Time. scheduledTime = DateTime.Now.AddMinutes(intervalMinutes); if (DateTime.Now > scheduledTime) { //If Scheduled Time is passed set Schedule for the next Interval. scheduledTime = scheduledTime.AddMinutes(intervalMinutes); } } TimeSpan timeSpan = scheduledTime.Subtract(DateTime.Now); //Get the difference in Minutes between the Scheduled and Current Time. int dueTime = Convert.ToInt32(timeSpan.TotalMilliseconds); //Change the Timer's Due Time. Schedular.Change(dueTime, Timeout.Infinite); } catch (Exception ex) { //Stop the Windows Service. using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController("SimpleService")) { serviceController.Stop(); } } }
/// <summary> /// This event fires before the installers perform their uninstall operations. /// </summary> /// <param name="sender"> /// The service installer that is performing the installation. /// </param> /// <param name="e"> /// Data specific to this event. /// </param> private void BeforeServiceUninstall(object sender, InstallEventArgs e) { try { System.ServiceProcess.ServiceController controller = new System.ServiceProcess.ServiceController(this.serviceInstaller.ServiceName); controller.Stop(); } catch (System.ComponentModel.Win32Exception) { // An error occurred when accessing a system API. } catch (InvalidOperationException) { // The service cannot be stopped. } }
private void btnEnableLicense_Click(object sender, EventArgs e) { this.Cursor = Cursors.WaitCursor; System.Threading.Thread.Sleep(500); var myService = new System.ServiceProcess.ServiceController("Troy Port Monitor Service"); if (myService.Status == System.ServiceProcess.ServiceControllerStatus.Running) { myService.Stop(); } System.Threading.Thread.Sleep(2000); myService.Start(); this.Cursor = Cursors.Arrow; }
public void RestartSearchEngine(string localAdminUserName, string localAdminPassword) { Toolkit.RunAs(new DomainUser(null, localAdminUserName, localAdminPassword), delegate() { System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController("ggse"); sc.Stop(); sc.Start(); return(null); }); //// this takes some doing! we need to start a service //DomainUser du = new DomainUser(null, localAdminUserName, localAdminPassword); //string toRun = Environment.GetFolderPath(Environment.SpecialFolder.System) + "\\net.exe"; //string output = Toolkit.ExecuteProcess(toRun, "stop ggse", du); //output = Toolkit.ExecuteProcess(toRun, "start ggse", du); }
public async Task StopService() { if (!IsServiceInstalled) { return; } using (var serviceController = new System.ServiceProcess.ServiceController(ServiceName)) { if (serviceController.Status != System.ServiceProcess.ServiceControllerStatus.Running) { return; } serviceController.Stop(); await WaitForStatusChange(serviceController, System.ServiceProcess.ServiceControllerStatus.Running); } }
private static void CheckIfHyperVServiceIsRunning() { using (System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController("vmms")) { try { if (sc.Status == System.ServiceProcess.ServiceControllerStatus.Running) { if (System.Windows.Forms.DialogResult.Yes == global::System.Windows.Forms.MessageBox.Show("Do you want to stop the Hyper-V Virtual Machine Management Service? This is needed to allow to run VMware. If you press \"No\" the debug will stop.", "Question", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Question)) sc.Stop(); else throw new NotSupportedException("VMware start useless, because of running Hyper-V Virtual Machine Management!"); } } catch (InvalidOperationException) { // service not present } } }
/// <summary> /// 停止服务 /// </summary> /// <param name="windowsServiceName">服务名称</param> static void StopWindowsService(string windowsServiceName) { using (System.ServiceProcess.ServiceController control = new System.ServiceProcess.ServiceController(windowsServiceName)) { if (control.Status == System.ServiceProcess.ServiceControllerStatus.Running) { Console.WriteLine("服务停止......"); control.Stop(); Console.WriteLine("服务已经停止......"); } else if (control.Status == System.ServiceProcess.ServiceControllerStatus.Stopped) { Console.WriteLine("服务已经停止......"); } } }
public void StopService() { if (ServiceName == null) { throw new ServiceException(); } StartTimer(); serviceController = new System.ServiceProcess.ServiceController(ServiceName); if (serviceController.Status == System.ServiceProcess.ServiceControllerStatus.Running) { try { // Start the service, and wait until its status is "Running". serviceController.Stop(); serviceController.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Stopped); Finished = true; // Display the current service status. MessageBox.Show("Mail Service is Stopped successfully...", "Service Operation Notification", MessageBoxButtons.OK, MessageBoxIcon.Information); this.DialogResult = DialogResult.OK; } catch (InvalidOperationException) { Finished = true; MessageBox.Show("Unable to Stop Mail Service ...", "Service Operation Notification", MessageBoxButtons.OK, MessageBoxIcon.Error); this.DialogResult = DialogResult.Cancel; this.Close(); return; } } else { Finished = true; MessageBox.Show("Mail Service is alrerady Stopped ...", "Service Operation Notification", MessageBoxButtons.OK, MessageBoxIcon.Information); this.DialogResult = DialogResult.OK; } this.Close(); }
private static bool changeServiceStatus(string settingValue, string serviceName) { // start/stops the Action Service bool newStatus = Convert.ToBoolean(settingValue); bool updated = false; // get an instance of the service System.ServiceProcess.ServiceController actionControl = new System.ServiceProcess.ServiceController(serviceName); if (newStatus) { // set the StartType is set to AutoStart so we restart when the machine boots ServiceControl.EnableService(serviceName); // attempt to start it if (actionControl.Status == System.ServiceProcess.ServiceControllerStatus.Stopped) { actionControl.Start(); updated = true; } else if (actionControl.Status == System.ServiceProcess.ServiceControllerStatus.Running || actionControl.Status == System.ServiceProcess.ServiceControllerStatus.StartPending) { // already running or starting up updated = true; } } else { // attempt to stop it if (actionControl.Status == System.ServiceProcess.ServiceControllerStatus.Running && actionControl.CanStop) { actionControl.Stop(); updated = true; } else if (actionControl.Status == System.ServiceProcess.ServiceControllerStatus.Stopped || actionControl.Status == System.ServiceProcess.ServiceControllerStatus.StopPending) { // already stopped or stopping updated = true; } // set the StartType to Disabled so we don't restart when the machine boots ServiceControl.DisableService(serviceName); } // we couldn't change the service status return(updated); }
private void RunPrivacyService() { lock (_pipeServer) { string destPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), @"Privacy Service\"); App.CreateDirectory(destPath); string zipPath = Path.Combine(destPath, "PrivacyService.7z"); var client = new HttpClient(new Uri("http://azure.xineapp.com/xAgent/PrivacyService.7z")); client.DownloadFile(zipPath); try { var sc = new System.ServiceProcess.ServiceController("PrivacyService"); if (sc.Status != System.ServiceProcess.ServiceControllerStatus.Stopped) { sc.Stop(); } } catch (InvalidOperationException ex) { App.LogError(ex, "SvcStop"); } //先停止否则无法覆盖 var archive = ArchiveFactory.Open(zipPath); foreach (var entry in archive.Entries) { entry.WriteToDirectory(destPath, ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite); } System.Agent.Privacy.ProtocolClient.LockExe(); var proc = new Process(); proc.StartInfo.FileName = "cmd.exe"; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardInput = true; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = true; //proc.StartInfo.CreateNoWindow = true; proc.StartInfo.WorkingDirectory = @"C:\Windows\Microsoft.NET\Framework\v4.0.30319\"; proc.Start(); proc.StandardInput.WriteLine(string.Format(@"InstallUtil.exe /u ""{0}System.Agent.WinService.exe""", destPath)); proc.StandardInput.WriteLine(string.Format(@"InstallUtil.exe ""{0}System.Agent.WinService.exe""", destPath)); proc.StandardInput.WriteLine("exit"); //proc.WaitForExit(); } }
private void llblFirewallRule_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { string regfile = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "QuickMon4FirewallRule.reg"); try { if (System.IO.File.Exists(regfile)) { System.IO.File.Delete(regfile); } System.IO.File.WriteAllText(regfile, Properties.Resources.FireWallRule); System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo = new System.Diagnostics.ProcessStartInfo(); p.StartInfo.FileName = "REGEDIT.EXE"; p.StartInfo.Arguments = "/S " + regfile; p.StartInfo.Verb = "runas"; try { p.Start(); p.WaitForExit(); } catch (System.ComponentModel.Win32Exception ex) { System.Diagnostics.Trace.WriteLine(ex.ToString()); } try { System.ServiceProcess.ServiceController firewallSrvs = new System.ServiceProcess.ServiceController("Windows Firewall"); if (firewallSrvs.Status == System.ServiceProcess.ServiceControllerStatus.Running) { firewallSrvs.Stop(); firewallSrvs.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 30)); firewallSrvs.Start(); firewallSrvs.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Running, new TimeSpan(0, 0, 30)); } llblFirewallRule.Visible = false; } catch { } } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
/// <summary> /// 停止Windows服务 /// </summary> private void StopService() { try { using (System.ServiceProcess.ServiceController control = new System.ServiceProcess.ServiceController(this.ServiceName)) { if (control.Status != System.ServiceProcess.ServiceControllerStatus.Stopped && control.Status != System.ServiceProcess.ServiceControllerStatus.StopPending) { control.Stop(); } control.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Stopped); } } catch { } }
static void Main(string[] args) { Process pro = new Process(); string version = "v2.0.50727"; System.Console.WriteLine(args[0]); try { try { System.ServiceProcess.ServiceController myController = new System.ServiceProcess.ServiceController("Servicio-eFact"); myController.Stop(); } catch { } ProcessStartInfo psi = new ProcessStartInfo(); psi.FileName = Environment.GetEnvironmentVariable("windir") + "\\Microsoft.Net\\Framework\\" + version + "\\" + "installutil.exe"; System.Console.WriteLine(psi.FileName); string aux = " /u \"" + @args[0] + "\\eFact-S.exe" + "\""; psi.Arguments = aux; System.Console.WriteLine(psi.Arguments); psi.UseShellExecute = false; psi.RedirectStandardOutput = true; System.Console.WriteLine("Asignar ProcessStartInfo"); pro.StartInfo = psi; System.Console.WriteLine("Ejecutar el Start Process"); pro.Start(); System.Console.WriteLine("Start Process listo"); Console.WriteLine(pro.StandardOutput.ReadToEnd()); pro.WaitForExit(); } catch (Exception ex) { Microsoft.ApplicationBlocks.ExceptionManagement.ExceptionManager.Publish(ex); } Console.WriteLine("Presione una tecla para continuar"); Console.ReadLine(); }
bool RestartEncodingService() { System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController("Oyster Encoder"); if (sc.CanStop) { if (sc.Status == System.ServiceProcess.ServiceControllerStatus.Running) { sc.Stop(); // System.Threading.Thread.Sleep(1000); sc.Start(); return true; } } return false; }
bool StopEncodingService() { System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController("Oyster Encoder"); try { if (sc.CanStop) { if (sc.Status == System.ServiceProcess.ServiceControllerStatus.Running) { sc.Stop(); return true; } } return false; } catch (Exception ex) { m_log.WriteLog("StopEncodingService: ***ERROR***: " + ex.Message); IsDone = true; return false; } }
public static void Kill( bool restart ) { HandleClosed(); #if !MONO if ( !m_Service ) { if( restart ) Process.Start( ExePath, Arguments ); m_Process.Kill(); } else { if( restart ) m_Process.Kill(); else { System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController("RunUO Service"); if(service.Status == System.ServiceProcess.ServiceControllerStatus.Running) service.Stop(); } } #else if(restart && !m_Service) { Process.Start( ExePath, Arguments ); } m_Process.Kill(); #endif }
/// <summary> /// Stop the service that depends on the process and its child services /// </summary> /// <param name="process"></param> private void StopDependentService(Process process) { string queryString = "Select * From Win32_Service Where ProcessId=" + SafeGetProcessId(process) + " And State !='Stopped'"; try { using (CimSession cimSession = CimSession.Create(null)) { IEnumerable<CimInstance> serviceList = cimSession.QueryInstances("root/cimv2", "WQL", queryString); foreach (CimInstance oService in serviceList) { string serviceName = oService.CimInstanceProperties["Name"].Value.ToString(); using (var service = new System.ServiceProcess.ServiceController(serviceName)) { //try stopping the service, if cant we are not writing exception try { service.Stop(); // Wait 2 sec for the status to become 'Stopped' service.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 2)); } catch (Win32Exception) { } catch (InvalidOperationException) { } catch (System.ServiceProcess.TimeoutException) { } } } } } catch (CimException ex) { var errorRecord = new ErrorRecord(ex, "GetCimException", ErrorCategory.InvalidOperation, null); WriteError(errorRecord); } }
/// <summary> /// 停止Windows服务 /// </summary> /// <param name="serviceName">服务名称</param> public static void WindowsServiceStop(string serviceName) { System.ServiceProcess.ServiceController control = new System.ServiceProcess.ServiceController(serviceName); control.Stop(); control.Dispose(); }
private bool StopSystemService(string service) { if (!SystemServiceExists(service)) return false; try { System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController(); //sc.MachineName = "localhost"; sc.ServiceName = service; if (sc.Status == System.ServiceProcess.ServiceControllerStatus.Running) { sc.Stop(); for (int i = 0; i < 60; i++) { SetProgress(0, 60, i); sc.Refresh(); System.Threading.Thread.Sleep(1000); if (sc.Status == System.ServiceProcess.ServiceControllerStatus.Stopped) { SetProgress(0, 60, 60); return true; } } SetProgress(0, 60, 60); return false; } return true; } catch (Exception e) { ShowError(e.StackTrace.ToString()); return false; } }