简体   繁体   中英

C# ServiceController not finding service when lookup uses parameter instead of hardcoded string

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM