public static string GetDriveType()
{
DriveInfo[] allDrives = DriveInfo.GetDrives();
foreach (DriveInfo drive in allDrives)
{
return DriveInfo.DriveType;
if(DriveType.CDRom)
{
return DriveInfo.Name;
}
}
}
正如大家们可能看到的,这段代码有点不对劲。基本上,我试图返回驱动器的名称,以便稍后在代码中使用,但前提是该驱动器是CDRom驱动器。我怎样才能检查驱动器的名称并将其返回,以便以后在我以编程方式打开CD驱动器时可以解释它?谢谢!
答案 0 :(得分:1)
如果有更多CD驱动器,您应该返回一个字符串列表:
public static List<string> GetCDDrives()
{
var cdDrives = DriveInfo.GetDrives().Where(drive => drive.DriveType == DriveType.CDRom);
return cdDrives?.Select(drive => drive.Name).ToList();
}
答案 1 :(得分:0)
我认为您需要以下内容:
public static string GetCDRomName()
{
// Get All drives
var drives = DriveInfo.GetDrives();
var cdRomName = null;
// Iterate though all drives and if you find a CdRom get it's name
// and store it to cdRomName. Then stop iterating.
foreach (DriveInfo drive in allDrives)
{
if(drive.DriveType == DriveType.CDRom)
{
cdRomName = drive.Name;
break;
}
}
// If any CDRom found returns it's name. Otherwise null.
return cdRomName;
}