Exemple #1
0
        public static ServiceConfig GetServiceConfig(SafeHandle serviceHandle)
        {
            // Stores the buffer size
            //
            uint bufferSize;

            // Call the native method once to attempt to get the needed buffer size
            //
            NativeMethods.QueryServiceConfig(serviceHandle, IntPtr.Zero, 0, out bufferSize);

            // Verify the last error was ERROR_INSUFFICIENT_BUFFER, if not, throw an exception
            //
            if (Marshal.GetLastWin32Error() != Win32Error.ERROR_INSUFFICIENT_BUFFER)
            {
                throw new Win32Exception();
            }

            // Allocate a buffer that is the necessary size
            //
            var serviceConfigPtr = Marshal.AllocHGlobal((int)bufferSize);

            try
            {
                // Call the native method again which should fill the buffer with the struct and throw an exception if that fails
                //
                if (!NativeMethods.QueryServiceConfig(serviceHandle, serviceConfigPtr, bufferSize, out bufferSize))
                {
                    throw new Win32Exception();
                }

                // Marshal the pointer to a struct and return a new ServiceConfig object
                //
                return
                    (new ServiceConfig(
                         (QUERY_SERVICE_CONFIG)Marshal.PtrToStructure(serviceConfigPtr, typeof(QUERY_SERVICE_CONFIG))));
            }
            finally
            {
                // Free the buffer
                //
                Marshal.FreeHGlobal(serviceConfigPtr);
            }
        }