我正在尝试查找驱动器的驱动器号(例如“C:\”)。
我知道驱动器的名称(例如“KINGSTON”),并将其存储在字符串drivename
中。
sDir
是保存结果的字符串。
DriveInfo[] drives = DriveInfo.GetDrives();
foreach (DriveInfo d in drives)
{
MessageBox.Show(d.Name);
if (d.VolumeLabel.Contains(drivename))
{
MessageBox.Show("Got Ya");
sDir = d.Name;
break;
}
}
这段代码在我看来应该可以工作,但是,虽然我有6个驱动器(drives.Lengt也显示6个),它只循环3个,没有进入if(从不显示“得到你的“msgbox”,然后跳出if-sentence,这段代码被包裹起来。
答案 0 :(得分:2)
DriveInfo.VolumeLabel
可能会抛出异常,您必须正确处理它。 http://msdn.microsoft.com/library/system.io.driveinfo.volumelabel
DriveInfo[] drives = DriveInfo.GetDrives();
foreach (DriveInfo d in drives)
{
MessageBox.Show(d.Name);
string volumeLabel = null;
try
{
volumeLabel = d.VolumeLabel;
}
catch (Exception ex)
{
if (ex is IOException || ex is UnauthorizedAccessException || ex is SecurityException)
MessageBox.Show(ex.Message);
else
throw;
}
if (volumeLabel != null && volumeLabel.Contains(drivename))
{
MessageBox.Show("Got Ya");
sDir = d.Name;
break;
}
}
您还可以查看DriveInfo.IsReady
。