private static Service ServiceFromManagementObject(ManagementBaseObject service) { try { string name = service.Properties["Name"].Value as string; Service s = new Service(name); s.Description = service.Properties["Description"].Value as string; s.Caption = service.Properties["Caption"].Value as string; s.DisplayName = service.Properties["DisplayName"].Value as string; s.Path = service.Properties["PathName"].Value as string; s.AcceptPause = (bool)service.Properties["AcceptPause"].Value; s.AcceptStop = (bool)service.Properties["AcceptStop"].Value; object pId = service.Properties["ProcessId"].Value; if (pId != null) { try { s.ProcessId = Convert.ToInt32(pId); s.ProcessorAffinity = GetProcessorAffinity(s.ProcessId); } catch { } } s.StartMode = ConvertStringToStartMode(service.Properties["StartMode"].Value as string); s.Account = service.Properties["StartName"].Value as string; s.Status = ConvertStringToServiceStatus(service.Properties["State"].Value as string); return s; } catch (Exception e) { Utils.Trace(e, "Unexpected error service from managerment object}."); return null; } }
/// <summary> /// Gets all installed Windows services. /// </summary> /// <returns>The list of intalled <see cref="Service"/>.</returns> public static Service[] GetAllServices() { List<Service> list = new List<Service>(); try { using (ManagementObjectSearcher objSearcher = new ManagementObjectSearcher("Select * from Win32_Service")) { using (ManagementObjectCollection winServices = objSearcher.Get()) { foreach (ManagementObject service in winServices) { Service s = ServiceFromManagementObject(service); list.Add(s); } } } } catch (Exception e) { Utils.Trace(e, "Unexpected error searching for all services."); } Service[] serviceArray = new Service[list.Count]; list.CopyTo(serviceArray); return serviceArray; }