错误地获取磁盘驱动器信息

本文关键字:信息 磁盘驱动器 获取 错误 | 更新日期: 2023-09-27 18:37:25

public static string GetDriveType()
{
    DriveInfo[] allDrives = DriveInfo.GetDrives();
    foreach (DriveInfo drive in allDrives) 
    {
        return DriveInfo.DriveType;
        if(DriveType.CDRom)
        {
            return DriveInfo.Name;
        }
    }
}

正如你们可能看到的那样,这段代码有很多问题。基本上,我尝试返回驱动器的名称以供稍后在代码中使用,但前提是驱动器是 CDRom 驱动器。如何检查驱动器的名称并将其返回,以便以后以编程方式打开 CD 驱动器时可以解释它?谢谢!

错误地获取磁盘驱动器信息

您应该返回一个字符串列表,以防有更多 CD 驱动器:

public static List<string> GetCDDrives()
{
    var cdDrives =  DriveInfo.GetDrives().Where(drive => drive.DriveType == DriveType.CDRom);
    return cdDrives?.Select(drive => drive.Name).ToList();
}

我认为您需要以下内容:

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;
}