Esempio n. 1
0
        private Win32ServiceControlHandle OpenService(
            Win32ServiceControlHandle serviceControlManagerHandle,
            string name)
        {
            var serviceHandle = Win32ServiceControl.OpenService(
                serviceControlManagerHandle,
                name,
                Win32ServiceControl.SERVICE_ACCESS.SERVICE_ALL_ACCESS);

            if (serviceHandle.IsInvalid)
            {
                ThrowNewWin32Exception(
                    "Failed to get a handle on '{0}' on {1}.",
                    name,
                    this.hostName);
            }

            return(serviceHandle);
        }
Esempio n. 2
0
        /// <summary>
        /// Hack method without having to impersonate admin user.
        /// </summary>
        internal static bool IsServiceInstalled(string hostName, string serviceName)
        {
            using (var scmHandle = OpenServiceControlManager(hostName, Win32ServiceControl.SCM_ACCESS.SC_MANAGER_CONNECT))
            {
                if (scmHandle.IsInvalid)
                {
                    throw new Win32Exception();
                }

                using (
                    var serviceHandle = Win32ServiceControl.OpenService(
                        scmHandle,
                        serviceName,
                        Win32ServiceControl.SERVICE_ACCESS.SERVICE_QUERY_STATUS))
                {
                    if (!serviceHandle.IsInvalid)
                    {
                        return(true);
                    }

                    var win32Exception = new Win32Exception();

                    switch (win32Exception.NativeErrorCode)
                    {
                    case 5:         // Access is denied, but that means it very likely exists!
                        return(true);

                    case 1060:      // The specified service does not exist as an installed service
                        return(false);

                    default:
                        throw win32Exception;
                    }
                }
            }
        }