Created
February 20, 2014 16:37
-
-
Save mmims/9117910 to your computer and use it in GitHub Desktop.
Eject CD/DVD in WinPE environment
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Collections.Generic; | |
| using System.Linq; | |
| using System.Runtime.InteropServices; | |
| using System.Text; | |
| namespace EjectMedia | |
| { | |
| class Program | |
| { | |
| static void Main(string[] args) | |
| { | |
| Console.WriteLine("args: {0}", args[0]); | |
| Console.WriteLine("Attempting to eject disc..."); | |
| EjectMedia.Eject(args[0]); | |
| } | |
| } | |
| class EjectMedia | |
| { | |
| // Constants used in DLL methods | |
| const uint GENERICREAD = 0x80000000; | |
| const uint OPENEXISTING = 3; | |
| const uint IOCTL_STORAGE_EJECT_MEDIA = 2967560; | |
| const int INVALID_HANDLE = -1; | |
| // File Handle | |
| private static IntPtr fileHandle; | |
| private static uint returnedBytes; | |
| // Use Kernel32 via interop to access required methods | |
| // Get a File Handle | |
| [DllImport("kernel32", SetLastError = true)] | |
| static extern IntPtr CreateFile(string fileName, uint desiredAccess, uint shareMode, IntPtr attributes, uint creationDisposition, uint flagsAndAttributes, IntPtr templateFile); | |
| [DllImport("kernel32", SetLastError=true)] | |
| static extern int CloseHandle(IntPtr driveHandle); | |
| [DllImport("kernel32", SetLastError = true)] | |
| static extern bool DeviceIoControl(IntPtr driveHandle, uint IoControlCode, IntPtr lpInBuffer, uint inBufferSize, IntPtr lpOutBuffer, uint outBufferSize, ref uint lpBytesReturned, IntPtr lpOverlapped); | |
| public static void Eject(string driveLetter) | |
| { | |
| try | |
| { | |
| // Create an handle to the drive | |
| fileHandle = CreateFile(driveLetter, GENERICREAD, 0, IntPtr.Zero, OPENEXISTING, 0, IntPtr.Zero); | |
| if ((int)fileHandle != INVALID_HANDLE) | |
| { | |
| // Eject the disk | |
| DeviceIoControl(fileHandle, IOCTL_STORAGE_EJECT_MEDIA, IntPtr.Zero, 0, IntPtr.Zero, 0, ref returnedBytes, IntPtr.Zero); | |
| } | |
| } | |
| catch | |
| { | |
| throw new Exception(Marshal.GetLastWin32Error().ToString()); | |
| } | |
| finally | |
| { | |
| // Close Drive Handle | |
| CloseHandle(fileHandle); | |
| fileHandle = IntPtr.Zero; | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment