Opening and closing a disk drive programmatically in C# is not all that difficult thanks to a useful API function called mciSendStringA. It is fairly straight forward and you can find many more examples of it at CodeProject for example.
In this article let's go over how to open and close a cd tray if you have more than one disk drive installed on your computer.
First you will need to define the function that will be opening the disk tray:
[DllImport("winmm.dll", EntryPoint = "mciSendString")] public static extern int mciSendStringA(string lpstrCommand, string lpstrReturnString, int uReturnLength, int hwndCallback);
If the code above does not compile try adding the following C# line at the very top of your source code:
To open the disk drive you need to send two command strings using mciSendStringA. The first one will assign a name to the desired drive. The second command will actually open the disk tray:
mciSendStringA("open " + driveLetter + ": type CDaudio alias drive" + driveLetter, returnString, 0, 0); mciSendStringA("set drive" + driveLetter + " door open", returnString, 0, 0);
To close the disk drive you need to send two command strings once again. The first one will be the same. The second command will now close the disk tray:
mciSendStringA("open " + driveLetter + ": type CDaudio alias drive" + driveLetter, returnString, 0, 0); mciSendStringA("set drive" + driveLetter + " door closed", returnString, 0, 0);
You might have noticed that the commands use the term CDaudio when refering to the disk drives. However the command works for both CD and DVD drives. I haven't tested it out on newer disk drives like BlueRay, but I would guess that it works just fine.
Also you can see the in downloadable source code that retrieving a list of installed disk drives is not very difficult. Use the DriveInfo.getDrives() method found under System.IO and check the DriveType of each one to be CDRom. Once again, it works for more than just plain CD drives.
The functions are lightweight and straight foward so you can easily add them to other C# projects and programmatically open and close disk drives...