1、啓動windows服務
ServiceController cs = new ServiceController();
cs.MachineName = "localhost";
cs.ServiceName = servicename;
cs.Refresh();
if (cs.Status == ServiceControllerStatus.Stopped
|| cs.Status == ServiceControllerStatus.StopPending)
{
cs.Start();
cs.Refresh();
}
2、修改windows服務啓動類型
C#啓動windows服務
修改註冊表
windows 服務的註冊表地址爲 :
[\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\ServiceName]
其中子鍵Start代表了啓動類型. 類如"Start"=dword:00000002
其中2爲Automatic, 3爲Manul, 4爲Disabled
C#啓動windows服務遇到的問題, 如果服務類型是Disabled, 那麼start方法就會引發異常。
一般的做法是先修改服務的啓動類型, 然後啓動該服務:
using Microsoft.Win32;
string keyPath = @"SYSTEM\CurrentControlSet\Services\ACPI";
RegistryKey key = Registry.LocalMachine.OpenSubKey(keyPath, true);
int val = -1;
bool bConverted = Int32.TryParse(key.GetValue("Start").ToString(), out val); if(bConverted)
{
if ( val == 4)
{
key.SetValue("Start", 3);
}
}
System.ServiceProcess.ServiceController service = new ServiceController("ACPI");
service.Start();
3、windows啓動,API