Open and Close the CD/DVD Drive Tray in C#

The quickest way to eject an optical drive from C# is the old Media Control Interface (MCI) in winmm.dll. You send it a text command such as set cdaudio door open and it does the rest. MCI dates back to Windows 3.1, but it still ships with Windows 11 and still works for this.

This is Windows-only. Target net8.0-windows and allow unsafe code for the [LibraryImport] source generator:

<PropertyGroup>
  <TargetFramework>net8.0-windows</TargetFramework>
  <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>

Add <UseWindowsForms>true</UseWindowsForms> if you call it from a WinForms app; the code itself does not need it.

Open and close the default drive

using System.Runtime.InteropServices;

uint result = Mci.Send("set cdaudio door open wait");
Console.WriteLine(result == 0 ? "Tray opened." : $"MCI error {result}");

Console.WriteLine("Press Enter to close the tray.");
Console.ReadLine();

result = Mci.Send("set cdaudio door closed wait");
Console.WriteLine(result == 0 ? "Tray closed." : $"MCI error {result}");

internal static partial class Mci
{
    [LibraryImport("winmm.dll", EntryPoint = "mciSendStringW",
        StringMarshalling = StringMarshalling.Utf16)]
    private static partial uint MciSendString(
        string lpszCommand, IntPtr lpszReturnString, uint cchReturn, IntPtr hwndCallback);

    public static uint Send(string command) =>
        MciSendString(command, IntPtr.Zero, 0, IntPtr.Zero);
}

mciSendString returns an MCIERROR, which is a 32-bit unsigned value where 0 means success. The second parameter is a buffer for commands that return text (such as status); these commands don’t, so the wrapper passes a null pointer and a length of zero. The wait flag makes the call return only after the drive has finished moving.

Pick a specific drive

cdaudio refers to the default CD device, which is the first optical drive. With more than one drive, open the one you want under an alias first, send it commands, then close the alias:

static void SetDoor(char driveLetter, bool open)
{
    string alias = $"drive{driveLetter}";

    Mci.Send($"open {driveLetter}: type cdaudio alias {alias}");
    Mci.Send($"set {alias} door {(open ? "open" : "closed")} wait");
    Mci.Send($"close {alias}");
}

SetDoor('E', open: true);

To find the drive letters, ask DriveInfo:

var opticalDrives = DriveInfo.GetDrives()
    .Where(d => d.DriveType == DriveType.CDRom)
    .Select(d => d.Name[0]);

When it does not work

A non-zero result or no movement is common, and usually not a bug in your code:

  • Most laptops and many desktops no longer have an optical drive at all. Check with DriveInfo first.
  • Slot-loading drives and most laptop drives can eject but cannot pull the tray back in. The close command succeeds or fails depending on the drive, but nothing moves.
  • Some USB drives and virtual drives (mounted ISO files also show up as CDRom) ignore door commands.

With wait, the call blocks while the drive moves. In a WinForms app, call it from an async event handler with await Task.Run(() => Mci.Send(...)) so the window doesn’t freeze for the second or two the tray takes.

The heavier alternative is opening the device with CreateFile and sending IOCTL_STORAGE_EJECT_MEDIA through DeviceIoControl. That works for any removable media, not just optical drives, but it is far more code for the same result.

On .NET Framework

[LibraryImport] requires .NET 7 or later. With [DllImport] the declaration is:

[DllImport("winmm.dll", CharSet = CharSet.Unicode)]
static extern uint mciSendString(
    string lpszCommand, IntPtr lpszReturnString, uint cchReturn, IntPtr hwndCallback);

Related examples

Leave a Comment