C# window服务操作
public int GetWindowsServiceStartType(String sServiceName) //判断服务状态是手动还是禁用还是自动 { string sState = ""; try { System.Diagnostics.ProcessStartInfo objProcessInf = new System.Diagnostics.ProcessStartInfo(); objProcessInf.FileName = "cmd.exe"; objProcessInf.UseShellExecute = false; //是否使用系统shell启动进程 objProcessInf.RedirectStandardError = true;//错误信息写入流 objProcessInf.RedirectStandardInput = true; objProcessInf.RedirectStandardOutput = true; //应用程序的输出写入流 objProcessInf.CreateNoWindow = true; //是否在新窗口启动该进程 objProcessInf.Arguments = "/c sc qc " + sServiceName; //启动参数 System.Diagnostics.Process objProcess = System.Diagnostics.Process.Start(objProcessInf); //启动进程 String sStateValue = objProcess.StandardOutput.ReadToEnd(); //读取应用程序输出的流 if (sStateValue.IndexOf("AUTO_START") > 0) { sState = "AUTO_START"; return 2; } if (sStateValue.IndexOf("DEMAND_START") > 0) { sState = "DEMAND_START"; return 3; } if (sStateValue.IndexOf("DISABLED") > 0) { sState = "DISABLED"; return 4; } return 0; } catch (Exception e) { sState = e.Message; return -1; } } public Boolean SetWindowsServiceStartType(String sServiceName, int iStartType) //设置服务状态是手动,自动,还是禁用 { try { System.Diagnostics.ProcessStartInfo objProcessInf = new System.Diagnostics.ProcessStartInfo(); objProcessInf.FileName = "cmd.exe"; objProcessInf.CreateNoWindow = false; objProcessInf.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; string sStartState = "boot"; switch (iStartType) { case 1: { sStartState = "system"; break; } case 2: { sStartState = "auto"; break; } case 3: { sStartState = "demand"; break; } case 4: { sStartState = "disabled"; break; } default: { break; } } objProcessInf.Arguments = "/c sc config " + sServiceName + " start= " + sStartState; System.Diagnostics.Process.Start(objProcessInf); return true; } catch { return false; } }
ServiceController sc = new ServiceController("Themes"); if (sc.Status.Equals(ServiceControllerStatus.Running)) { sc.Stop(); sc.Refresh(); } if ((sc.Status.Equals(ServiceControllerStatus.Stopped)) || (sc.Status.Equals(ServiceControllerStatus.StopPending))) { sc.Start(); sc.Refresh(); }
bool exist = false; ServiceController[] Services = ServiceController.GetServices(); for (int i = 0; i < Services.Length; i++) { if (Services[i].DisplayName.ToString() == textBox1.Text.Trim()) exist = true; } return exist;