开发者

How to Eject CD-ROM [duplicate]

This question already has answers here: Cl开发者_如何学运维osed 11 years ago.

Possible Duplicates:

Windows CDROM Eject

Open CD/DVD door with a Windows API call?

I have looked around and can't find a simple solution to what I want to do.

I want to open a CD-Rom from my C# app. It should check if the media is in fact a cd- rom and then open it. Is there a quick solution to this or am I missing something?


Check this URL, it has both managed and unmanaged code for .net

http://bytes.com/topic/c-sharp/answers/273513-how-eject-cd-rom-c

Try below code :

using System;
using System.Text;
using System.Runtime.InteropServices;
namespace EjectMedia
{
class Program
{
   static void Main(string[] args)
   {
     // My CDROM is on drive E:
         EjectMedia.Eject(@"\\.\E:");
    }
}

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;
         }
  }
 }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜