Check if a service exists on a particular machine without using exception handling

前端 未结 3 1165
青春惊慌失措
青春惊慌失措 2020-12-15 02:47

Don\'t know if there is a better way to do this, so that is the reason for the question. I can check if a service exists on a particular machine with the following code:

3条回答
  •  难免孤独
    2020-12-15 03:24

    Built on top of Mike's answer. Same concept as Dictionary.TryGetValue.

        /// 
        /// Gets a  given the specified .
        /// 
        /// The name of the service.
        /// The  associated with the name.
        /// 
        ///  if the  exists; otherwise .
        /// 
        private static bool TryGetService(string pServiceName, out ServiceController pService)
        {
            pService = ServiceController.GetServices()
                .FirstOrDefault(serviceController => serviceController.ServiceName == pServiceName);
    
            return pService != null;
        }
    

提交回复
热议问题