【问题标题】:Set Drive VolumeLabel设置驱动器卷标签
【发布时间】:2011-08-25 07:22:16
【问题描述】:

我正在开发一个小型实用程序,我想在其中更改连接到计算机的闪存驱动器上的卷标。我知道 DriveInfo 有能力做到这一点,但我不知道如何完成它。如果有人有代码示例,我将不胜感激。
这是我目前拥有的:

DriveInfo[] allDrives = DriveInfo.GetDrives();
foreach (DriveInfo d in allDrives)
{
    if (d.IsReady && d.DriveType == DriveType.Removable)
    {
        //set volume label here
    }
}

【问题讨论】:

  • 所有个可移动驱动器上设置相同的卷标不能(不应该)你的想法。不要随意更改驱动器数据。得到用户的同意。
  • 它不会“随便”完成,它实际上是由用户(我)按下按钮完成的。它是自动重命名驱动器,所以我不必手动执行数百次。

标签: c# drive driveinfo


【解决方案1】:

【讨论】:

  • 我确实看过它,但我对如何实现它很感兴趣。
  • 当你使用“d.VolumeLabel = newLabel;”时会发生什么?我错过了什么吗?是否抛出异常?
【解决方案2】:

谢谢詹姆斯!我不知道为什么我有这么多问题,但你让我走上了正确的道路。

这是设置驱动器标签的最终代码。对于使用它的任何其他人,它将更改连接到系统的任何可移动驱动器的名称。如果您只需要更改特定驱动器型号的名称,您可以使用 WMI 的Win32_DiskDrive 来缩小范围。

public void SetVolumeLabel(string newLabel)
{
    DriveInfo[] allDrives = DriveInfo.GetDrives();
    foreach (DriveInfo d in allDrives)
    {
        if (d.IsReady && d.DriveType == DriveType.Removable)
        {
            d.VolumeLabel = newLabel;
        }
    }
}

public string VolumeLabel { get; set; }

// Setting the drive name
private void button1_Click(object sender, EventArgs e)
{
    SetVolumeLabel("FlashDrive");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-01
    • 2020-04-26
    • 1970-01-01
    • 2011-04-18
    • 2021-09-26
    • 2017-10-09
    相关资源
    最近更新 更多