Is there an easy way to detect if a disc is inserted in the DVD drive? I don't care what kind of disc (CD, DVD or Blu-Ray)?
Use WMI to detect if disk in CD/DVD drive:
foreach (var drive in DriveInfo.GetDrives()
.Where(d => d.DriveType == DriveType.CDRom))
MessageBox.Show(drive.Name + " " + drive.IsReady.ToString());
from here.
DriveType Enumeration can help you what kind of disc:
CDRom : The drive is an optical disc device, such as a CD or DVD-ROM.
Fixed : The drive is a fixed disk.
Network : The drive is a network drive.
NoRootDirectory The drive does not have a root directory.
Ram : The drive is a RAM disk.
Removable : The drive is a removable storage device, such as a floppy disk drive or a USB flash drive.
Unknown : The type of drive is unknown.
for kind of CD/DVD/Blue-Ray see IMAPI_MEDIA_PHYSICAL_TYPE enumeration:
UNKNOWN
CDROM
CDR
CDRW
DVDROM
DVDRAM
DVDPLUSR
DVDPLUSRW
DVDPLUSR_DUALLAYER
DVDDASHR
DVDDASHRW
DVDDASHR_DUALLAYER
DISK
DVDPLUSRW_DUALLAYER
HDDVDROM
HDDVDR
HDDVDRAM
BDROM
BDR
BDRE
MAX
your code may be like this:
public bool IsDiscAvailable(int driveNumber)
{
MsftDiscMaster2Class discMaster = new MsftDiscMaster2Class();
string id = discMaster[driveNumber];
MsftDiscRecorder2Class recorder = new MsftDiscRecorder2Class();
recorder.InitializeDiscRecorder(id);
MsftDiscFormat2DataClass dataWriter = new MsftDiscFormat2DataClass();
if (dataWriter.IsRecorderSupported(recorder))
{
dataWriter.Recorder = recorder;
}
else
{
Console.WriteLine("Recorder not supported");
return false;
}
if (dataWriter.IsCurrentMediaSupported(recorder))
{
var media = dataWriter.CurrentPhysicalMediaType;
if (media == IMAPI_MEDIA_PHYSICAL_TYPE.IMAPI_MEDIA_TYPE_UNKNOWN)
{
Console.WriteLine("Unknown media or no disc");
}
else
{
Console.WriteLine("Found disc type {0}", media);
return true;
}
}
else
{
Console.WriteLine("Disc absent or invalid.");
}
return false;
}
from here.
How to Detect CD-ROM is loaded in the CD-ROM drive
From above link
using System;
using System.Management;
class Application
{
public static void Main()
{
SelectQuery query =
new SelectQuery( "select * from win32_logicaldisk where drivetype=5" );
ManagementObjectSearcher searcher =
new ManagementObjectSearcher(query);
foreach( ManagementObject mo in searcher.Get() )
{
// If both properties are null I suppose there's no CD
if(( mo["volumename"] != null) || (mo["volumeserialnumber"] != null))
{
Console.WriteLine("CD is named: {0}", mo["volumename"]);
Console.WriteLine("CD Serial Number: {0}", mo["volumeserialnumber"]);
}
else
{
Console.WriteLine("No CD in Unit");
}
}
// Here to stop app from closing
Console.WriteLine("\nPress Return to exit.");
Console.Read();
}
}
Related
I am working on an application where I am placing the json files at particular directory in connected android device. Android device has an application which used to read the data from json files and then files are deleted. I am using MediaDevices library to list and connect devices in WPF application.
public Form1()
{
InitializeComponent();
bindDevices();
}
private void bindDevices()
{
try
{
devices = MediaDevice.GetDevices();
var test = devices.Select(x => x).ToList();
List<deviceDetails> deviceNames = (from d in test
select new deviceDetails
{
deviceID = d.DeviceId,
deviceName = d.FriendlyName == "" ? d.Description : d.FriendlyName
}).ToList();
foreach (MediaDevice device in devices)
{
device.Connect();
lblBattery.Text = device.PowerLevel.ToString();
try
{
getDirectory(device);
}
catch (Exception ex)
{
}
finally
{
device.Disconnect();
}
}
comboBox1.ValueMember = "deviceID";
comboBox1.DisplayMember = "deviceName";
comboBox1.DataSource = deviceNames;
//var device = devices.FirstOrDefault().FriendlyName == "" ? devices.FirstOrDefault().Description : devices.FirstOrDefault().FriendlyName;
//label2.Text = device;
}
catch (Exception ex)
{
MessageBox.Show("Error : -" + ex.Message);
label2.Text = "Can not connect to device";
}
}
Above mentioned steps are working fine.
Problem: Sometimes, while device is connected through USB, if I check on file explorer at PC, it shows me json files but if I check in android device files were removed. If, I am trying to delete those files through PC then it show message files are locked. Once, I disconnect/connect the device again then files are removed from device directory.
How, I can reset the connectivity of device so connection will be reset through code.
im using huawei e359
Hello im creating a simple program. where my code will connect the 3g modem to the internet. because a part of my program need to access the internet.
i did some search how to do this using c#
this is my code for adding entry
string deviceName = null;
path = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User);
using (RasPhoneBook pbk = new RasPhoneBook())
{
pbk.Open(path);
foreach (var item in RasDevice.GetDevices())
{
if (item.DeviceType.ToString().ToLower() == "modem")
{
deviceName = item.Name;
}
}
RasDevice device = RasDevice.GetDevices().Where(o => o.Name == deviceName && o.DeviceType == RasDeviceType.Modem).First();
if (!RasEntry.Exists("Your Entry", path))
{
RasEntry entry = RasEntry.CreateDialUpEntry("Your Entry", "+00000000000", device);
pbk.Entries.Add(entry);
}
}
and this is the code for dialing the device
using (RasDialer dialer = new RasDialer())
{
dialer.EntryName = "Your Entry";
dialer.PhoneBookPath = path;
dialer.AllowUseStoredCredentials = true;
dialer.Dial();
}
this is the error, it prompts when i dial the device
The remote computer did not respond. To make sure that the server can be reached, ping the remote computer.
So far I have the following:
// Gets all the drives
DriveInfo[] allDrives = DriveInfo.GetDrives();
// checks if any CD-Rom exists in the drives
var cdRomExists = allDrives.Any(x => x.DriveType == DriveType.CDRom);
// Get all the cd roms
var cdRoms = allDrives.Where(x=>x.DriveType==DriveType.CDRom);
if (cdRomExists.Equals(true))
{
// Loop through the cd roms collection
foreach(var cdRom in cdRoms)
{
Console.WriteLine("Drive {0}", cdRom.Name);
Console.WriteLine(" File type: {0}", cdRom.DriveType);
if (cdRom.IsReady == true)
{
if (cdRom.DriveType == DriveType.CDRom)
{
DirectoryInfo di = new DirectoryInfo(cdRom.RootDirectory.Name);
var file = di.GetFiles("*.csv", SearchOption.AllDirectories).FirstOrDefault();
if (file == null)
{
errorwindow.Message = LanguageResources.Resource.File_Not_Found;
dialogService.ShowDialog(LanguageResources.Resource.Error, errorWindow);
}
else
{
foreach (FileInfo info in di.GetFiles("*.csv", SearchOption.AllDirectories))
{
Debug.Print(info.FullName);
ImportCSV(info.FullName);
break; // only looking for the first one
}
}
}
}
else if (cdRom.IsReady == false)
{
errorwindow.Message = LanguageResources.Resource.CDRom_Not_Ready;
dialogService.ShowDialog(LanguageResources.Resource.Error, errorWindow);
}
}
}
else
{
errorwindow.Message = LanguageResources.Resource.CDRom_Error;
dialogService.ShowDialog(LanguageResources.Resource.Error, errorWindow);
}
The problem with the following is, an error message pops up twice in a row to indicate if there is no CD-ROM in the drive because my computer contains both a DVD and blu ray Drive. If there is a CD Rom that contains CSV file, it gets successfully imported but another message pops up because of the foreach loop that runs to the blu ray drive and pops up.
I only want to display one error message for each of these situations:
-If there is no CD Rom that is ready and contains csv in the drive
-If the CD Rom drive does not contain csv
I think my logic is too convoluted and I need help adjusting my logic statements.
You just need to keep track of whether at least one of the drives worked for you. If none of them did, then you want to output the error message. There's also some other stuff you could do (no need to do the Any/Where, no need to do .Equals(true), etc. And more specifically, no need to continually check if its the right kind of drive. The cdRoms collection will only contain drives with the right type because that's what you specify in your Where clause.
// Gets all the drives
DriveInfo[] allDrives = DriveInfo.GetDrives();
// Get all the cd roms
var cdRoms = allDrives.Where(x=>x.DriveType==DriveType.CDRom);
if (cdRoms.Count() > 0)
{
bool found = false;
// Loop through the cd roms collection
foreach(var cdRom in cdRoms)
{
Console.WriteLine("Drive {0}", cdRom.Name);
Console.WriteLine(" File type: {0}", cdRom.DriveType);
if (cdRom.IsReady == true)
{
DirectoryInfo di = new DirectoryInfo(cdRom.RootDirectory.Name);
var file = di.GetFiles("*.csv", SearchOption.AllDirectories).FirstOrDefault();
if (file == null)
{
errorwindow.Message = LanguageResources.Resource.File_Not_Found;
dialogService.ShowDialog(LanguageResources.Resource.Error, errorWindow);
}
else
{
foreach (FileInfo info in di.GetFiles("*.csv", SearchOption.AllDirectories))
{
Debug.Print(info.FullName);
ImportCSV(info.FullName);
found = true;
break; // only looking for the first one
}
}
}
else
{
Debug.Print(string.Format("Drive {0} is not ready", cdRom.Name));
}
}
if (!found)
{
errorwindow.Message = LanguageResources.Resource.CDRom_Not_Ready;
dialogService.ShowDialog(LanguageResources.Resource.Error, errorWindow);
}
}
else
{
errorwindow.Message = LanguageResources.Resource.CDRom_Error;
dialogService.ShowDialog(LanguageResources.Resource.Error, errorWindow);
}
Your code can be rewritten to following:
var cdRoms = allDrives.Where(x => x.DriveType == DriveType.CDRom && x.IsReady);
if (cdRoms.Any())
{
foreach(var cdRom in cdRoms)
{
Console.WriteLine("Drive {0}", cdRom.Name);
Console.WriteLine(" File type: {0}", cdRom.DriveType);
var di = new DirectoryInfo(cdRom.RootDirectory.Name);
var file = di.GetFiles("*.csv", SearchOption.AllDirectories).FirstOrDefault();
if (file == null)
{
errorwindow.Message = LanguageResources.Resource.File_Not_Found;
dialogService.ShowDialog(LanguageResources.Resource.Error, errorWindow);
}
else
{
foreach (var info in di.GetFiles("*.csv", SearchOption.AllDirectories))
{
Debug.Print(info.FullName);
ImportCSV(info.FullName);
break;
}
}
}
}
else
{
errorwindow.Message = LanguageResources.Resource.CDRom_Error;
dialogService.ShowDialog(LanguageResources.Resource.Error, errorWindow);
}
Changes:
No need to use Where and Any like you did, filter the CD-Rom drives from all the drives and see if any exist
Only select drives that are CD-Rom drives and are ready
Use var where possible, let the compiler do the job
This is my approach to your problem:
bool anyCdrom = false;
bool anyReady = false;
bool fileFound = false;
// Loop through the cd roms collection
foreach(var cdRom in DriveInfo.GetDrives().Where(drive => drive.DriveType == DriveType.CDRom))
{
anyCdrom = true;
Console.WriteLine("Drive {0}", cdRom.Name);
Console.WriteLine(" File type: {0}", cdRom.DriveType);
if (cdRom.IsReady) // You may want to put in into the intial where
{
anyReady = true;
foreach (string file in Directory.EnumerateFiles(cdRom.RootDirectory.Name, "*.csv", SearchOption.AllDirectories))
{
fileFound = true;
Debug.Print(file);
ImportCSV(file);
break; // only looking for the first one
}
if(fileFound)
break;
}
}
if(!anyCdrom)
{
errorwindow.Message = LanguageResources.Resource.CDRom_Error;
dialogService.ShowDialog(LanguageResources.Resource.Error, errorWindow);
}
else if(!anyReady)
{
errorwindow.Message = LanguageResources.Resource.CDRom_Not_Ready;
dialogService.ShowDialog(LanguageResources.Resource.Error, errorWindow);
}
else if(!fileFound)
{
errorwindow.Message = LanguageResources.Resource.File_Not_Found;
dialogService.ShowDialog(LanguageResources.Resource.Error, errorWindow);
}
It only prints an error when:
there is no cdrom
there is no cdrom ready
there is no csv file in any ready cdrom
How can I determine if a drive is a external drive plugged in through usb ? I checked the DriveInfo.DriveType but with my 1TB external drive plugged in through usb it shows up as a fixed drive.
Thoughts ?
Based on a comment from Floyd Pink I used this link. This allows me to determine whether a device is external or not.
public bool IsProjectOnExternalDisk(string driveLetter)
{
bool retVal = false;
driveLetter = driveLetter.TrimEnd('\\');
// browse all USB WMI physical disks
foreach (ManagementObject drive in new ManagementObjectSearcher("select DeviceID, MediaType,InterfaceType from Win32_DiskDrive").Get())
{
// associate physical disks with partitions
ManagementObjectCollection partitionCollection = new ManagementObjectSearcher(String.Format("associators of {{Win32_DiskDrive.DeviceID='{0}'}} " + "where AssocClass = Win32_DiskDriveToDiskPartition", drive["DeviceID"])).Get();
foreach (ManagementObject partition in partitionCollection)
{
if (partition != null)
{
// associate partitions with logical disks (drive letter volumes)
ManagementObjectCollection logicalCollection = new ManagementObjectSearcher(String.Format("associators of {{Win32_DiskPartition.DeviceID='{0}'}} " + "where AssocClass= Win32_LogicalDiskToPartition", partition["DeviceID"])).Get();
foreach (ManagementObject logical in logicalCollection)
{
if (logical != null)
{
// finally find the logical disk entry
ManagementObjectCollection.ManagementObjectEnumerator volumeEnumerator = new ManagementObjectSearcher(String.Format("select DeviceID from Win32_LogicalDisk " + "where Name='{0}'", logical["Name"])).Get().GetEnumerator();
volumeEnumerator.MoveNext();
ManagementObject volume = (ManagementObject)volumeEnumerator.Current;
if (driveLetter.ToLowerInvariant().Equals(volume["DeviceID"].ToString().ToLowerInvariant()) &&
(drive["MediaType"].ToString().ToLowerInvariant().Contains("external") || drive["InterfaceType"].ToString().ToLowerInvariant().Contains("usb")))
{
retVal = true;
break;
}
}
}
}
}
}
return retVal;
}
Using WMI Select * from Win32_LogicalDisk as in Royi Namir's answer and DriveInfo.DriveType show my external type as 'Local Disk' which I can't use to determine whether the drive is external.
you can use WMI
with
Select * from Win32_LogicalDisk
http://www.jpsoftwaretech.com/vba/using-wmi-services-in-vba/drive-information-local-network-mapped-drives/
there you have
Select Case .DriveType
Case 0
strDriveType = "Unknown"
Case 1
strDriveType = "No Root Directory"
Case 2
strDriveType = "Removable Disk"
Case 3
strDriveType = "Local Disk"
Case 4
strDriveType = "Network Drive"
Case 5
strDriveType = "Compact Disc"
Case 6
strDriveType = "RAM Disk"
End Select
I came across this question looking for a way to get a list of external drives, and I found that I could simplify a lot by updating the syntax. Also, some USB drives are UAS or USB attached SCSI, and the interface for those types of drives will actually show up as SCSI and not USB. From my tests, I've found that just checking for the terms "external" and "removable" in the physical disk's media type is sufficient.
public List<DriveInfo> getExternalDrives()
{
var drives = DriveInfo.GetDrives();
var externalDrives = new List<DriveInfo>();
var allPhysicalDisks = new ManagementObjectSearcher("select MediaType, DeviceID from Win32_DiskDrive").Get();
foreach (var physicalDisk in allPhysicalDisks)
{
var allPartitionsOnPhysicalDisk = new ManagementObjectSearcher($"associators of {{Win32_DiskDrive.DeviceID='{physicalDisk["DeviceID"]}'}} where AssocClass = Win32_DiskDriveToDiskPartition").Get();
foreach(var partition in allPartitionsOnPhysicalDisk)
{
if (partition == null)
continue;
var allLogicalDisksOnPartition = new ManagementObjectSearcher($"associators of {{Win32_DiskPartition.DeviceID='{partition["DeviceID"]}'}} where AssocClass = Win32_LogicalDiskToPartition").Get();
foreach(var logicalDisk in allLogicalDisksOnPartition)
{
if (logicalDisk == null)
continue;
var drive = drives.Where(x => x.Name.StartsWith(logicalDisk["Name"] as string, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
var mediaType = (physicalDisk["MediaType"] as string).ToLowerInvariant();
if (mediaType.Contains("external") || mediaType.Contains("removable"))
externalDrives.Add(drive);
}
}
}
return externalDrives;
}
I am developing a C# .NET 2.0 application wherein I need to scan for an attached HID. How can this be done? Because it is a HID, Windows does not assign a COM port to it. I only need to programmatically determine if the device is attached. Thank you.
ADDITIONAL INFORMATION
When I connect the USB device to my computer two entries appear under Human Interface Devices in the Device Manager. Clicking into their Properties yields this information in their respective Details tabs:
HID-compliant device
Device Instance Id: HID\VID_1795&PID_6004\7&2694D932&0&0000
USB Human Interface Device
Device Instance Id: USB\VID_1795&PID_6004\B973000000EB0D00
In the WMI Code Creator select these options:
Namespace: root\WMI
Class: MSWmi_PnPInstanceNames
Select InstanceNames from the Results box for the following code:
using System;
using System.Management;
using System.Windows.Forms;
namespace WMISample
{
public class MyWMIQuery
{
public static void Main()
{
try
{
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\WMI",
"SELECT * FROM MSWmi_PnPInstanceNames");
foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("-----------------------------------");
Console.WriteLine("MSWmi_PnPInstanceNames instance");
Console.WriteLine("-----------------------------------");
Console.WriteLine("InstanceName: {0}", queryObj["InstanceName"]);
}
}
catch (ManagementException e)
{
MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
}
}
}
}
Here is an example of enumerating Hid devices on Windows:
public static ConnectedDeviceDefinition GetDeviceDefinition(string deviceId, SafeFileHandle safeFileHandle)
{
try
{
var hidAttributes = GetHidAttributes(safeFileHandle);
var hidCollectionCapabilities = GetHidCapabilities(safeFileHandle);
var manufacturer = GetManufacturer(safeFileHandle);
var serialNumber = GetSerialNumber(safeFileHandle);
var product = GetProduct(safeFileHandle);
return new ConnectedDeviceDefinition(deviceId)
{
WriteBufferSize = hidCollectionCapabilities.OutputReportByteLength,
ReadBufferSize = hidCollectionCapabilities.InputReportByteLength,
Manufacturer = manufacturer,
ProductName = product,
ProductId = (ushort)hidAttributes.ProductId,
SerialNumber = serialNumber,
Usage = hidCollectionCapabilities.Usage,
UsagePage = hidCollectionCapabilities.UsagePage,
VendorId = (ushort)hidAttributes.VendorId,
VersionNumber = (ushort)hidAttributes.VersionNumber,
DeviceType = DeviceType.Hid
};
}
catch (Exception)
{
return null;
}
}
Full class here: https://github.com/MelbourneDeveloper/Device.Net/blob/master/src/Hid.Net/Windows/WindowsHidDeviceFactory.cs
API Calls here: https://github.com/MelbourneDeveloper/Device.Net/blob/master/src/Hid.Net/Windows/HidAPICalls.cs
Here is a similar thing for Windows 10 (UWP):
public async Task<IEnumerable<ConnectedDeviceDefinition>> GetConnectedDeviceDefinitions(FilterDeviceDefinition deviceDefinition)
{
var aqsFilter = GetAqsFilter(deviceDefinition.VendorId, deviceDefinition.ProductId);
var deviceInformationCollection = await wde.DeviceInformation.FindAllAsync(aqsFilter).AsTask();
var deviceDefinitions = deviceInformationCollection.Select(d => GetDeviceInformation(d, DeviceType));
var deviceDefinitionList = new List<ConnectedDeviceDefinition>();
foreach (var deviceDef in deviceDefinitions)
{
var connectionInformation = await TestConnection(deviceDef.DeviceId);
if (connectionInformation.CanConnect)
{
await Task.Delay(1000);
deviceDef.UsagePage = connectionInformation.UsagePage;
deviceDefinitionList.Add(deviceDef);
}
}
return deviceDefinitionList;
}
Code:https://github.com/MelbourneDeveloper/Device.Net/blob/77439b1ab0f4b3ad97376e4e62c7efac0a749783/src/Device.Net.UWP/UWPDeviceFactoryBase.cs#L47
Android (https://github.com/MelbourneDeveloper/Device.Net/blob/77439b1ab0f4b3ad97376e4e62c7efac0a749783/src/Usb.Net.Android/AndroidUsbDeviceFactory.cs#L31):
public Task<IEnumerable<ConnectedDeviceDefinition>> GetConnectedDeviceDefinitions(FilterDeviceDefinition deviceDefinition)
{
return Task.Run<IEnumerable<ConnectedDeviceDefinition>>(() =>
{
//TODO: Get more details about the device.
return UsbManager.DeviceList.Select(kvp => kvp.Value).Where(d => deviceDefinition.VendorId == d.VendorId && deviceDefinition.ProductId == d.ProductId).Select(GetAndroidDeviceDefinition).ToList();
});
}
Using Hid.Net, you can enumerate devices in the same way on any platform like below. See the full article.
var devices = await DeviceManager.Current.GetConnectedDeviceDefinitions(new FilterDeviceDefinition { VendorId = 0x1209, ProductId = 0x53C1 });
foreach (var device in devices)
{
Debug.WriteLine(device.DeviceId);
}