///<summary>Gets the service name for the currently running process. Throws if it cannot find a service.</summary> public static string GetCurrentProcessServiceName() { int processId = Process.GetCurrentProcess().Id; ODWmiService curService = ODWmiService.GetServices().FirstOrDefault(x => x.ProcessId == processId); if (curService == null) { throw new Exception("Unable to find service name."); } return(curService.Name); }
///<summary>Returns true if a service is currently installed with the specified service name. ///Optionally pass in the file info for the desired service and this method will also return true if there is a service utilizing the same ///executable.</summary> public static bool HasService(string serviceName, FileInfo serviceFileInfo = null) { //Old way is to search the registry. This can tend to throw exceptions based on Windows user permissions, especially if runnong on a Domain Controller. //Let's try it this way first so as not to break any back-compatibility. try { List <ServiceController> listServices = GetServices(); foreach (ServiceController service in listServices) { if (serviceName == service.ServiceName) { return(true); } if (serviceFileInfo == null) { continue; } RegistryKey hklm = Registry.LocalMachine; hklm = hklm.OpenSubKey(@"System\CurrentControlSet\Services\" + service.ServiceName); string installedServicePath = hklm.GetValue("ImagePath").ToString().Replace("\"", ""); if (installedServicePath.Contains(serviceFileInfo.FullName)) { return(true); } } return(false); } catch (Exception e) { e.DoNothing(); } //Querying the registry failed so let's try querying Window Management Interface (WMI). //If this throws also then let it throw. It means we absolutely cannot determine that status of this service. var asWmi = ODWmiService.GetServices(); if (asWmi.Any(x => string.Compare(x.Name, serviceName, true) == 0)) //Name match. Already exists. { return(true); } //Check the new path against all installed service paths. Typically installed service paths are encapsulated by \" \" so use Contains(). if (serviceFileInfo != null && asWmi.Any(x => x.PathName.ToLower().Contains(serviceFileInfo.FullName.ToLower()))) //Path match. Already exists. { return(true); } //Service does not exist. return(false); }