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