Exemplo n.º 1
0
        public string GetServiceDescription(string serviceName)
        {
            const int bufferSize = 1024 * 8;

            IntPtr service   = IntPtr.Zero;
            IntPtr bufferPtr = IntPtr.Zero;

            try
            {
                // Open the service
                service = OpenService(serviceName, ServiceWin32Api.ServiceAccessRights.SERVICE_QUERY_CONFIG);

                int dwBytesNeeded = 0;

                // Allocate memory for struct
                bufferPtr = Marshal.AllocHGlobal(bufferSize);
                int queryResult = ServiceWin32Api.QueryServiceConfig2(
                    service,
                    ServiceWin32Api.ServiceConfig2InfoLevel.SERVICE_CONFIG_DESCRIPTION,
                    bufferPtr,
                    bufferSize,
                    out dwBytesNeeded);

                if (queryResult == 0)
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error(), "Unable to query the Service configuration.");
                }

                // Cast the buffer to a SERVICE_DESCRIPTION struct
                ServiceWin32Api.SERVICE_DESCRIPTION desc =
                    (ServiceWin32Api.SERVICE_DESCRIPTION)Marshal.PtrToStructure(bufferPtr, typeof(ServiceWin32Api.SERVICE_DESCRIPTION));

                return(desc.lpDescription);
            }
            finally
            {
                // Clean up
                if (bufferPtr != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(bufferPtr);
                }

                if (service != IntPtr.Zero)
                {
                    ServiceWin32Api.CloseServiceHandle(service);
                }
            }
        }