2016-03-05 37 views
-1
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

你的问题很琐碎,示例代码一个非确定的混淆(多重归还陈述),这意味着总体上的问题还不清楚。 – TomTom

+0

这个问题完全是我的要求。我只是想知道如何检查驱动器的特定类型并将它们返回以后使用。 –

+0

''//返回DriveInfo.DriveType;' –

回答

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

@Downvoter,你能解释一下有什么问题吗?谢谢 – Christos

+0

我会在早上测试它,但这看起来像一个工作代码。我的错误是不正确地使用返回语句。我真的只需要一个。这应该工作得很好,谢谢! –

+0

@TAYLORBROWN不用客气。我很高兴我帮助:) – Christos

1

你应该在的情况下返回一个字符串列表有更多的CD驱动器:

public static List<string> GetCDDrives() 
{ 
    var cdDrives = DriveInfo.GetDrives().Where(drive => drive.DriveType == DriveType.CDRom); 

    return cdDrives?.Select(drive => drive.Name).ToList(); 
} 
+0

恕我直言,最好的答案(c#6) – cutzero

相关问题