473,395 Members | 1,763 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

How to eject CD ROM in C#.

Hi all,

I want to access, detect, eject(open and close) CD Rom using C#. How i can do this..?

--

Mähésh Kumär. R
cyberiafreak
Nov 17 '05 #1
4 22773
Hi!

One way is to use wmi.

public class cEjectMedia

{

private const int INVALID_HANDLE_VALUE = -1;

private const int GENERIC_READ = unchecked((int)0x80000000);

private const int GENERIC_WRITE = unchecked((int)0x40000000);

private const int FILE_SHARE_READ = unchecked((int)0x00000001);

private const int FILE_SHARE_WRITE = unchecked((int)0x00000002);

private const int OPEN_EXISTING = unchecked((int)3);

private const int FSCTL_LOCK_VOLUME = unchecked((int)0x00090018);

private const int FSCTL_DISMOUNT_VOLUME = unchecked((int)0x00090020);

private const int IOCTL_STORAGE_EJECT_MEDIA = unchecked((int)0x002D4808);

private const int IOCTL_STORAGE_MEDIA_REMOVAL = unchecked((int)0x002D4804);

[DllImport("kernel32.dll", EntryPoint="CreateFileW", CharSet=CharSet.Unicode, SetLastError=true)]

private static extern IntPtr CreateFile(

string lpFileName,

int dwDesiredAccess,

int dwShareMode,

IntPtr lpSecurityAttributes,

int dwCreationDisposition,

int dwFlagsAndAttributes,

IntPtr hTemplateFile);

[DllImport("kernel32.dll", ExactSpelling=true, SetLastError=true)]

private static extern bool CloseHandle(IntPtr handle);

[DllImport("kernel32.dll", ExactSpelling=true, SetLastError=true)]

private static extern bool DeviceIoControl(

IntPtr hDevice,

int dwIoControlCode,

byte[] lpInBuffer,

int nInBufferSize,

byte[] lpOutBuffer,

int nOutBufferSize,

out int lpBytesReturned,

IntPtr lpOverlapped );

public cEjectMedia()

{

//

// TODO: Fügen Sie hier die Konstruktorlogik hinzu

//

}

public bool EjectMedia(string sPhysicalDrive)

{

bool ok = false;

bool KarteKannEntnommenWerden = false;

// Schritt 1: Volume öffnen // Laufwerk anpassen! //

IntPtr h = CreateFile( @"\\.\" + sPhysicalDrive, GENERIC_READ,

FILE_SHARE_READ | FILE_SHARE_WRITE,

IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero );

if( h.ToInt32() == -1 )

return false;

while( true )

{

// Schritt 2: Volume sperren

for( int i = 0; i < 10; i++ )

{

int nout = 0;

ok = DeviceIoControl( h, FSCTL_LOCK_VOLUME,

null, 0, null, 0, out nout, IntPtr.Zero );

if( ok )

break;

Thread.Sleep( 500 );

}

if( !ok )

break;

// Schritt 3: Volume dismounten

int xout = 0;

ok = DeviceIoControl( h, FSCTL_DISMOUNT_VOLUME,

null, 0, null, 0, out xout, IntPtr.Zero );

if( !ok )

break;

// ab hier kann die Karte ohne Datenverlust

// entnommen werden

KarteKannEntnommenWerden = true;

// Schritt 4: Prevent Removal Of Volume

byte[] flg = new byte[1];

flg[0] = 0; // 0 = false

int yout = 0;

ok = DeviceIoControl( h,

IOCTL_STORAGE_MEDIA_REMOVAL, flg, 1,

null, 0, out yout, IntPtr.Zero );

if( !ok )

break;

// Schritt 5: Eject Media

ok = DeviceIoControl( h,

IOCTL_STORAGE_EJECT_MEDIA,

null, 0, null, 0, out xout, IntPtr.Zero );

break;

}

// Schritt 6: Close Handle

ok = CloseHandle( h );

return KarteKannEntnommenWerden;

}

}

Then you can eject the cd-rom drive:

cEjectMedia myEjectMedia = new cEjectMedia();

myEjectMedia.EjectMedia(sDiskDrive);

You can also use it to remove usb drives.

Greetz

Michael

Nov 17 '05 #2
Thnkz for this unmanaged approach to solve this problem..but i'm searching something in managed code approach. I mean again we are importing the unmanaged DLL into our App, but i'm looking something in managed approach...??

I'm wondering how to get this simple thing in .NET..?

Mahe
"Matthias Pfeffer" <kn*****@gmx.net> wrote in message news:eq**************@TK2MSFTNGP09.phx.gbl...
Hi!

One way is to use wmi.

public class cEjectMedia

{

private const int INVALID_HANDLE_VALUE = -1;

private const int GENERIC_READ = unchecked((int)0x80000000);

private const int GENERIC_WRITE = unchecked((int)0x40000000);

private const int FILE_SHARE_READ = unchecked((int)0x00000001);

private const int FILE_SHARE_WRITE = unchecked((int)0x00000002);

private const int OPEN_EXISTING = unchecked((int)3);

private const int FSCTL_LOCK_VOLUME = unchecked((int)0x00090018);

private const int FSCTL_DISMOUNT_VOLUME = unchecked((int)0x00090020);

private const int IOCTL_STORAGE_EJECT_MEDIA = unchecked((int)0x002D4808);

private const int IOCTL_STORAGE_MEDIA_REMOVAL = unchecked((int)0x002D4804);

[DllImport("kernel32.dll", EntryPoint="CreateFileW", CharSet=CharSet.Unicode, SetLastError=true)]

private static extern IntPtr CreateFile(

string lpFileName,

int dwDesiredAccess,

int dwShareMode,

IntPtr lpSecurityAttributes,

int dwCreationDisposition,

int dwFlagsAndAttributes,

IntPtr hTemplateFile);

[DllImport("kernel32.dll", ExactSpelling=true, SetLastError=true)]

private static extern bool CloseHandle(IntPtr handle);

[DllImport("kernel32.dll", ExactSpelling=true, SetLastError=true)]

private static extern bool DeviceIoControl(

IntPtr hDevice,

int dwIoControlCode,

byte[] lpInBuffer,

int nInBufferSize,

byte[] lpOutBuffer,

int nOutBufferSize,

out int lpBytesReturned,

IntPtr lpOverlapped );

public cEjectMedia()

{

//

// TODO: Fügen Sie hier die Konstruktorlogik hinzu

//

}

public bool EjectMedia(string sPhysicalDrive)

{

bool ok = false;

bool KarteKannEntnommenWerden = false;

// Schritt 1: Volume öffnen // Laufwerk anpassen! //

IntPtr h = CreateFile( @"\\.\" + sPhysicalDrive, GENERIC_READ,

FILE_SHARE_READ | FILE_SHARE_WRITE,

IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero );

if( h.ToInt32() == -1 )

return false;

while( true )

{

// Schritt 2: Volume sperren

for( int i = 0; i < 10; i++ )

{

int nout = 0;

ok = DeviceIoControl( h, FSCTL_LOCK_VOLUME,

null, 0, null, 0, out nout, IntPtr.Zero );

if( ok )

break;

Thread.Sleep( 500 );

}

if( !ok )

break;

// Schritt 3: Volume dismounten

int xout = 0;

ok = DeviceIoControl( h, FSCTL_DISMOUNT_VOLUME,

null, 0, null, 0, out xout, IntPtr.Zero );

if( !ok )

break;

// ab hier kann die Karte ohne Datenverlust

// entnommen werden

KarteKannEntnommenWerden = true;

// Schritt 4: Prevent Removal Of Volume

byte[] flg = new byte[1];

flg[0] = 0; // 0 = false

int yout = 0;

ok = DeviceIoControl( h,

IOCTL_STORAGE_MEDIA_REMOVAL, flg, 1,

null, 0, out yout, IntPtr.Zero );

if( !ok )

break;

// Schritt 5: Eject Media

ok = DeviceIoControl( h,

IOCTL_STORAGE_EJECT_MEDIA,

null, 0, null, 0, out xout, IntPtr.Zero );

break;

}

// Schritt 6: Close Handle

ok = CloseHandle( h );

return KarteKannEntnommenWerden;

}

}

Then you can eject the cd-rom drive:

cEjectMedia myEjectMedia = new cEjectMedia();

myEjectMedia.EjectMedia(sDiskDrive);

You can also use it to remove usb drives.

Greetz

Michael

Nov 17 '05 #3
This is another approach using a dll, full simple app provided

Hope this helps

Publicjoe

C# Tutorial at http://www.publicjoe.f9.co.uk/csharp/tut.html
C# Ebook at http://www.publicjoe.f9.co.uk/csharp/samples/ebook.html - 72
Chapters
VB Ebook at http://www.publicjoe.f9.co.uk/vbnet/samples/ebook.html - 28
Chapters
C++ Ebook at http://www.publicjoe.f9.co.uk/cppt/samples/ebook.html - 8
Chapters
Java Ebook at http://www.publicjoe.f9.co.uk/java/samples/ebook.html - 2
Chapters
Mirrors at http://dowhileloop.com/publicjoe/ and
http://publicjoe.justbe.com/

///--- Beginning of code ---///

using System;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

public class CDFrm : Form
{
private System.ComponentModel.Container components = null;

private Button btn1;
private Button btn2;

// Constructor
public CDFrm()
{
InitializeComponent();
}

// Clean up any resources being used.
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

// Initialize form components
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();

this.Text = "CD Demo";
this.Size = new Size( 200, 100 );

// Button initialization and setup
btn1 = new Button();
btn1.Text = "Open";
btn1.Location = new Point( 20, 15 );
btn1.Size = new Size( 70, 20 );

btn2 = new Button();
btn2.Text = "Close";
btn2.Location = new Point( 110, 15 );
btn2.Size = new Size( 70, 20 );

// Add the Buttons to the Form
this.Controls.Add( btn1 );
this.Controls.Add( btn2 );

// Add Event for Button Click
btn1.Click += new EventHandler(btnEject_Click);
btn2.Click += new EventHandler(btnClose_Click);
}

// The main entry point for the application.
[STAThread]
static void Main()
{
Application.Run( new CDFrm() );
}

// Event for Open Button Click
private void btnEject_Click( object sender, System.EventArgs e )
{
int ret = mciSendString( "set cdaudio door open", null, 0,
IntPtr.Zero );
}

// Event for Close Button Click
private void btnClose_Click( object sender, System.EventArgs e )
{
int ret = mciSendString( "set cdaudio door closed", null, 0,
IntPtr.Zero );
}

// DLL access
[DllImport( "winmm.dll", EntryPoint="mciSendStringA",
CharSet=CharSet.Ansi )]
protected static extern int mciSendString( string lpstrCommand,
StringBuilder
lpstrReturnString,
int uReturnLength,
IntPtr hwndCallback );
}

///--- End of code ---///
Nov 17 '05 #4
Hmm, Great link and thnkz for your resource Mike..really i'm finding lot of
resources over there...

Thnkz,
Mahesh
/cyberiafreak/

"Publicjoe" <mi**@publicjoe.co.uk> wrote in message
news:ux**************@TK2MSFTNGP10.phx.gbl...
This is another approach using a dll, full simple app provided

Hope this helps

Publicjoe

C# Tutorial at http://www.publicjoe.f9.co.uk/csharp/tut.html
C# Ebook at http://www.publicjoe.f9.co.uk/csharp/samples/ebook.html - 72
Chapters
VB Ebook at http://www.publicjoe.f9.co.uk/vbnet/samples/ebook.html - 28
Chapters
C++ Ebook at http://www.publicjoe.f9.co.uk/cppt/samples/ebook.html - 8
Chapters
Java Ebook at http://www.publicjoe.f9.co.uk/java/samples/ebook.html - 2
Chapters
Mirrors at http://dowhileloop.com/publicjoe/ and
http://publicjoe.justbe.com/

///--- Beginning of code ---///

using System;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

public class CDFrm : Form
{
private System.ComponentModel.Container components = null;

private Button btn1;
private Button btn2;

// Constructor
public CDFrm()
{
InitializeComponent();
}

// Clean up any resources being used.
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

// Initialize form components
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();

this.Text = "CD Demo";
this.Size = new Size( 200, 100 );

// Button initialization and setup
btn1 = new Button();
btn1.Text = "Open";
btn1.Location = new Point( 20, 15 );
btn1.Size = new Size( 70, 20 );

btn2 = new Button();
btn2.Text = "Close";
btn2.Location = new Point( 110, 15 );
btn2.Size = new Size( 70, 20 );

// Add the Buttons to the Form
this.Controls.Add( btn1 );
this.Controls.Add( btn2 );

// Add Event for Button Click
btn1.Click += new EventHandler(btnEject_Click);
btn2.Click += new EventHandler(btnClose_Click);
}

// The main entry point for the application.
[STAThread]
static void Main()
{
Application.Run( new CDFrm() );
}

// Event for Open Button Click
private void btnEject_Click( object sender, System.EventArgs e )
{
int ret = mciSendString( "set cdaudio door open", null, 0,
IntPtr.Zero );
}

// Event for Close Button Click
private void btnClose_Click( object sender, System.EventArgs e )
{
int ret = mciSendString( "set cdaudio door closed", null, 0,
IntPtr.Zero );
}

// DLL access
[DllImport( "winmm.dll", EntryPoint="mciSendStringA",
CharSet=CharSet.Ansi )]
protected static extern int mciSendString( string lpstrCommand,
StringBuilder
lpstrReturnString,
int uReturnLength,
IntPtr hwndCallback );
}

///--- End of code ---///

Nov 17 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Allen St.Clair | last post by:
How can I eject a CD tray (Drive Letter is known)? Thx~
1
by: Prakru | last post by:
Hello guys, I get compilation error for the following code in MS VC++ 6 compiler: I thought that if the Eject is called with no args, then the Player::Eject () should be called. But it...
1
by: Hai Ly Hoang [MT00KSTN] | last post by:
In my application, i want to flush all data to USB and eject it (like select Safe Remove from tray icon). Is it possible ? How to to that ? Thanks a lot
3
by: Tony | last post by:
I wish to be able to eject either a pc card or compact flash card programmatically Is there any way to achieve this in with C#? TIA Tony
0
by: MT00KSTN - Hai Ly Hoang | last post by:
In my application, I want to command to eject the USB drive (flash disk) (like select Safe Remove from the tray icon). How to do that ? Thank in advance
3
by: Joe Cool | last post by:
OK, I know you have to be able to do this. I have searched VB help, this newsgroup, and google in general and I can't find any sample code or instructions on how to eject the cd/dvd device tray...
0
by: David Penne | last post by:
I have SBS 2003 and am using the built in tape backup. My question is about the registry key "Eject Tape Flag". I understand that this is an undocumented key and the only articles I can find...
0
by: mvrpavan | last post by:
How can I eject a CDROM drive on network programmatically
4
by: John Devlon | last post by:
Hi Does anyone know how to eject a cd/dvd on a drive? Thanx John
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.