可以使用System.ServiceProcess.ServiceController這個類允許連接到正在運行或者已停止的服務、對其進行操作或獲取有關它的信息。ServiceController 提供了開始和停止服務的方法(Start, Stop)。
但是這個類並沒有提供修改服務啟動類型的方法,可以通過C#調用cmd來修改
參考網上的這個方法:
//設置服務的啟動類型
//sServiceName服務名稱
//iStartType要設置的啟動類型 2:自動,3:手動,4:禁用
//返回成功狀態 true:成功,false:失敗
代碼如下:
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;
}
}
代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.ServiceProcess;
using Microsoft.Win32;
namespace Service
{
public class ClassService
{
private string ServiceName; //服務名稱
private ServiceController sc;
/// <summary>
/// 服務操作
/// </summary>
/// <param name="ServiceName">服務名稱</param>
public ClassService(string ServiceName)
{
this.ServiceName = ServiceName;
this.sc = new ServiceController(ServiceName);
}
/// <summary>
/// 啟動服務
/// </summary>
/// <returns></returns>
public bool StartService()
{
try
{
if (sc.Status != ServiceControllerStatus.Running)
sc.Start();
else
return false;
}
catch (Exception)
{
return false;
}
return true;
}
/// <summary>
/// 停止服務
/// </summary>
/// <returns></returns>
public bool StopService()
{
try
{
if (sc.Status != ServiceControllerStatus.Stopped)
sc.Stop();
else
return false;
}
catch (Exception)
{
return false;
}
return true;
}
/// <summary>
/// 重啟服務
/// </summary>
/// <returns></returns>
public bool RestartService()
{
if (StopService())
{
if (StartService())
return true;
else
return false;
}
else
return false;
}
/// <summary>
/// 獲取服務啟動類型
/// </summary>
/// <returns>2:自動 3:手動 4:禁用 0:獲取失敗</returns>
public int GetServiceStartMode()
{
int Mode = 0;
try
{
RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\services\" + ServiceName);
Mode = Convert.ToInt32(key.GetValue("Start"));
key.Close();
}
catch (Exception)
{
return 0;
}
return Mode;
}
/// <summary>
/// 設置服務啟動類型
/// </summary>
/// <param name="Mode">2:自動 3:手動 4:禁用</param>
/// <returns></returns>
public bool SetServiceStartMode(int Mode)
{
try
{
RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\services\" + ServiceName, true);
key.SetValue("Start", Mode);
key.Close();
}
catch (Exception)
{
return false;
}
return true;
}
}
}