【问题标题】:How can I read a "drive label" or "volume name" in .NET?如何在 .NET 中读取“驱动器标签”或“卷名”?
【发布时间】:2008-12-16 18:18:57
【问题描述】:

您能否展示在 .NET 中读取驱动器标签或卷名的示例代码?我觉得这需要 WMI,但我讨厌“下拉”到 WMI,因为它就像下拉到基于字符串的 SQL 查询中,因为某些对象可能不存在于某些版本的操作系统或用户上可能无权查询某些数据。我很高兴确信我对 WMI 的看法是错误的......

【问题讨论】:

    标签: .net wmi


    【解决方案1】:

    不需要 WMI。以下将获取所有卷标:

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

    【讨论】:

    • 或者只是 (new DriveInfo("C")).VolumeLabel
    • 这是正确答案。我发现最好获取一个 DriveInfo 实例,然后要求 VolumeLabel 作为单独的语句,因为 drive.VolumeLabel 在“驱动器未准备好”时抛出 IOException,例如空 CDROM。有关如何避免此异常的任何提示?吞下去?
    【解决方案2】:

    调用 DriveInfo.GetDrives 以获取驱动器信息数组。然后看看DriveInfo.VolumeLabel

    【讨论】:

      【解决方案3】:

      您可以使用 System.IO.DriveInfo 来获取驱动器列表。请参见以下示例:

      注意:CDRom 驱动器类型没有卷名。

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

      【讨论】:

      • CDROM 和其他可移动驱动器在包含带有标签的磁盘时带有标签。
      • 我想避免错误的最好方法是在请求 VolumeLabel 之前测试 driveInfo.IsReady。
      猜你喜欢
      • 2013-10-11
      • 2011-08-25
      • 1970-01-01
      • 1970-01-01
      • 2014-10-23
      • 1970-01-01
      • 1970-01-01
      • 2011-02-20
      • 2021-09-26
      相关资源
      最近更新 更多