I'm having some issues with finding a service running on my local machine, but only when I'm using the parameter string instead of a hardcoded string (which I added to debug the problem).
My method looks like this:
public bool CheckIfServiceIsRunning(string serviceName)
{
try
{
var services = ServiceController.GetServices();
var service = services.FirstOrDefault(s => s.DisplayName == serviceName);
var test = services.FirstOrDefault(s => s.DisplayName == "MongoDB");
if (service == null)
{
return false;
}
return service.Status.Equals(ServiceControllerStatus.Running);
}
catch (InvalidOperationException ex)
{
Log.Info(ex.Message);
throw new InvalidOperationException(ex.Message);
}
}
Results of running this code with parameter "MongoDB":
service = null
test = System.ServiceProcess.ServiceController object with the MongoDB service
Edit: Using the following comparison tells me the strings aren't equal:
if (string.Compare(serviceName, "MongoDB", StringComparison.Ordinal) == 0)
{
Console.WriteLine("same string");
}
The method itself looks fine, there is something wrong with the parameter you parse, take a good look at what you are actually putting in the method. Try using serviceName.Trim()
, strings can get tricky about whitespace characters before and/or after.
You can also set a breakpoint inside a method and check what exactly that serviceName
contains.