You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# WinForm如何从选定文件路径获取对应磁盘的卷标?

Get Volume Label from a File Path

You're already halfway there! Since you've got the root folder path using Path.GetPathRoot(), the next step is to use that root to fetch the corresponding drive's volume label via the DriveInfo class.

Step-by-Step Implementation

Here's how to tie it all together with your existing code:

First, start with your selected file path:

string selectedFilePath = @"E:\Pictures\mypic.png";

Retrieve the root directory (which you already have working):

string rootFolder = Path.GetPathRoot(selectedFilePath); // Returns "E:\"

Now, use this root path to create a DriveInfo object and get the volume label. Adding checks for drive readiness and validity helps avoid unexpected exceptions:

if (!string.IsNullOrEmpty(rootFolder))
{
    try
    {
        DriveInfo drive = new DriveInfo(rootFolder);
        if (drive.IsReady) // Ensure the drive is accessible (important for removable media)
        {
            string volumeLabel = drive.VolumeLabel;
            Console.WriteLine($"Volume Label for {rootFolder}: {volumeLabel}"); // Outputs "Volume Label for E:\: LocalDisc"
        }
        else
        {
            Console.WriteLine($"Drive {rootFolder} is not ready or accessible.");
        }
    }
    catch (ArgumentException ex)
    {
        Console.WriteLine($"Invalid drive path: {ex.Message}");
    }
}

Explanation

  • DriveInfo(rootFolder) creates an instance representing the drive associated with your root path.
  • IsReady verifies the drive is connected and readable (critical for USB drives or network drives that might be disconnected).
  • VolumeLabel directly returns the label you need—in your example, this will be "LocalDisc".

Alternative: Reuse Your Existing Drive Loop

If you prefer to work with your existing loop over all drives, you can filter for the matching root path:

string selectedFilePath = @"E:\Pictures\mypic.png";
string rootFolder = Path.GetPathRoot(selectedFilePath);

foreach (var drive in DriveInfo.GetDrives())
{
    if (drive.Name.Equals(rootFolder, StringComparison.OrdinalIgnoreCase))
    {
        if (drive.IsReady)
        {
            Console.WriteLine($"Drive Name: {drive.VolumeLabel}"); // Outputs "Drive Name: LocalDisc"
        }
        break; // Exit the loop once we find the matching drive
    }
}

Either approach works—choose the one that fits your code structure best!

内容的提问来源于stack exchange,提问作者Sajith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:48:41