I tried using WMI to detect new media insertion in Disk Drive using following code. But is there managed solution like using loop in background thread with DriveInfo.GetDrives? Which is best way to do this? I'm getting 'Disk is not in the drive please insert disk' dialog with abort, retry and continue button on other pc when i tried the following code? On may machine it works fine.
private void DriveWatcher()
{
try
{
var wqlEventQuery = new WqlEventQuery
{
EventClassName = "__InstanceModificationEvent",
WithinInterval = new TimeSpan(0, 0, 1),
Condition =
@"TargetInstance ISA 'Win32_LogicalDisk' and TargetInstance.DriveType = 5"
};
var connectionOptions = new ConnectionOptions
{
EnablePrivileges = true,
Authority = null,
Authentication = AuthenticationLevel.Default
};
var managementScope = new ManagementScope("\\root\\CIMV2", connectionOptions);
ManagementEventWatcher = new ManagementEventWatcher(managementScope, wqlEventQuery);
ManagementEventWatcher.EventArrived += CdrEventArrived;
ManagementEventWatcher.Start();
}
catch (ManagementException e)
{
MessageBox.Show(e.Message, e.GetType().ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void CdrEventArrived(object sender, EventArrivedEventArgs e)
{
var wmiDevice = (ManagementBaseObject) e.NewEvent["TargetInstance"];
if (wmiDevice.Properties["VolumeName"].Value != null)
GetDrives();
else
GetDrives();
}
private void GetDrives()
{
if (InvokeRequired)
{
Invoke(new GetDrivesDelegate(GetDrives));
}
else
{
toolStripComboBoxDrives.Items.Clear();
DriveInfo[] drives = DriveInfo.GetDrives();
_drives = new Dictionary<string, DriveInfo>();
int selectedIndex = 0;
foreach (DriveInfo drive in drives)
{
if (drive.DriveType.Equals(DriveType.CDRom))
{
if (drive.IsReady)
{
string name = string.Format("{0} ({1})", drive.VolumeLabel, drive.Name.Substring(0, 2));
int selectedDrive = toolStripComboBoxDrives.Items.Add(name);
_drives.Add(name, drive);
selectedIndex = selectedDrive;
}
else
{
toolStripComboBoxDrives.Items.Add(drive.Name);
_drives.Add(drive.Name, drive);
}
}
}
toolStripComboBoxDrives.SelectedIndex = selectedIndex;
}
}
Basically what i'm doing is on form load event called Drive Watcher. So when disk is inserted ready disk will be listed first in combo box and user can eject the drive easily.
Refer Following Code:
Referance Link:
http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/1ecb74cd-d193-40f5-9aa3-47a3c9adb4ea/
Stack Link:
Detecting if disc is in DVD drive
you can try with these code :
if it works on your machine and does not work on any other window based machine, then you have to rebuild/repair/re-register that machine's WMI classes. This will help you in that.
I'm going with following solution. It's 100% managed solution. It's not using WMI and works great.
You can use this as follows.