Search code examples
c#.netvb.netserviceservicecontroller

Searching the ServiceController array using Array.Findall?


I'm rusty at the moment coding in .NET again, and am trying to avoid doing a For Each loop, playing with Array.Findall.

I want to grab an array of all services installed on the machine, and then pass a string to search it's Friendly Display Name for any matches; if found, return the matches along with their actual service name.

i.e. Pass the string "Calibre", which will search all services for any that have "Calibre" in their Display Name. I'm doing this as a sort of "fuzzy search" in case the actual service name isn't known, and in case there happens to be more than one that match the passed string, a bunch of services won't be started/stopped.

I have:

Dim strServiceName = "Calibre"  
Dim scServices() As ServiceController = ServiceController.GetServices()  
Dim value2() As String = Array.FindAll(scServices, Function(x) x.DisplayName.ToLower().Contains(strServiceName))

But get the error:

Value of type '1-dimensional array of System.ServiceProcess.ServiceController' cannot be converted to '1-dimensional array of String' because 'System.ServiceProcess.ServiceController' is not derived from 'String'."

I know I'm probably missing something real simple, but it's eluding me at the moment, lol.


Solution

  • The genetic type of Array.FindAll<T> returned is the same as the genetic type of array, which is ServiceController here.

    If you want to get all the services' name which contains the specific name in their DisplayName, you should select the DisplayName out from the ServiceController like this:

    Dim value2() As String = Array.FindAll(scServices, Function(x) x.DisplayName.ToLower().Contains(strServiceName))
                                  .Select(Function(x) x.DisplayName).ToArray()