tags:

views:

1091

answers:

3

Can you show sample code for reading a drive label or volume name in .NET? I get the sense this requires WMI, but I am loathe to "drop-down" into WMI because it is like dropping down into a string-based SQL query in the sense that certain objects may not exist on certain versions of OSes or the user may not have the right to query certain data. I will be happy to be convinced that I'm wrong about WMI ...

+8  A: 

No WMI required. The following will get all volume labels:

var labels = from drive in DriveInfo.GetDrives()
             select drive.VolumeLabel

HTH, Kent

Kent Boogaart
Or just (new DriveInfo("C")).VolumeLabel
Greg Dean
This is the correct answer. I find it is better to get a DriveInfo instance and then ask for the VolumeLabel as a separate statement because drive.VolumeLabel throws an IOException when "the drive is not ready", such as an empty CDROM. Any tips on how to avoid this exception? Just swallow it?
flipdoubt
+3  A: 

Call DriveInfo.GetDrives to get an array of drive information. Then look at DriveInfo.VolumeLabel

Sean
+1  A: 

You could use System.IO.DriveInfo to get the list of drives. See following example:

Note: CDRom drive types do not have a volume name.

Using System.IO;
.
.
.
DriveInfo[] driveInfoList = DriveInfo.GetDrives();
foreach (DriveInfo drive in driveInfoList)
{
    if (drive.DriveType != DriveType.CDRom)
       textBox1.Text += String.Format("Name:{0} Volume:{1}\r\n", drive.Name, drive.VolumeLabel);
    else
       textBox1.Text += String.Format("Name:{0}\r\n", drive.
}
Ron Todosichuk
CDROM and other removable drives have labels when they contain disks with labels.
flipdoubt
I guess the best way to avoid errors is to test driveInfo.IsReady before asking for the VolumeLabel.
flipdoubt