Ejemplo n.º 1
0
        /// <summary>
        /// Gets the boot sector of a given drive.
        /// <remarks>The drive letter must follow this pattern X:</remarks>
        /// </summary>
        /// <param name="driveLetter">The drive letter in this format X:</param>
        /// <returns>The boot sector of the specified drive.</returns>
        public static BootSector GetBootSector(string driveLetter)
        {
            byte[] bootSectorData = new byte[BootSectorSize];
            string drive          = @"\\.\" + driveLetter;

            IntPtr hardDiskPointer = SystemIO.OpenFile(drive);

            // Seeks the start of the partition
            SystemIO.SeekAbsolute(hardDiskPointer, 0);

            // Read the first reserved sector of the drive data (Boot Sector)
            // The data should be read with a chunk of 512 X byte.
            SystemIO.ReadBytes(hardDiskPointer, bootSectorData, BootSectorSize);

            // Release IO handle
            SystemIO.CloseHandle(hardDiskPointer);

            // Prevent the GC from messing up with the position of the buffer in the heap.
            GCHandle pinnedBootSectorData = GCHandle.Alloc(bootSectorData, GCHandleType.Pinned);

            // Marshaling the buffer into a valid data structucture.
            var bootSector = (BootSector)Marshal.PtrToStructure(
                pinnedBootSectorData.AddrOfPinnedObject(),
                typeof(BootSector)
                );

            // Free up the pinned buffer.
            pinnedBootSectorData.Free();

            return(bootSector);
        }