4

如何使用设备路径中的驱动器号解析路径?

例如,转换

\Device\HarddiskVolume4\Windows\System32\RuntimeBroker.exe

进入

C:\Windows\System32\RuntimeBroker.exe

假设HarddiskVolume4映射到C:这台计算机上。

我找到了这个问题,但我想在 C# 中使用它。

4

1 回答 1

1
string devicePath = @"\Device\HarddiskVolume4\Windows\System32\RuntimeBroker.exe";
string driveLetterPath = DevicePathMapper.FromDevicePath(devicePath);

// driveLetterPath == C:\Windows\System32\RuntimeBroker.exe

由于我们想要一个带有驱动器号的路径,我们需要\Device\HarddiskVolume4用正确的驱动器号替换,例如C:. 为此使用QueryDosDevice并将 dos 设备映射到每个驱动器号。然后我们就可以搜索替换dos设备路径了。

这是一种可能的实现方式。它使用内部扩展方法:

public static class DevicePathMapper {
    [DllImport("Kernel32.dll", CharSet = CharSet.Unicode)]
    private static extern uint QueryDosDevice([In] string lpDeviceName, [Out] StringBuilder lpTargetPath, [In] int ucchMax);

    public static string FromDevicePath(string devicePath) {
        var drive = Array.Find(DriveInfo.GetDrives(), d => devicePath.StartsWith(d.GetDevicePath(), StringComparison.InvariantCultureIgnoreCase));
        return drive != null ?
            devicePath.ReplaceFirst(drive.GetDevicePath(), drive.GetDriveLetter()) :
            null;
    }

    private static string GetDevicePath(this DriveInfo driveInfo) {
        var devicePathBuilder = new StringBuilder(128);
        return QueryDosDevice(driveInfo.GetDriveLetter(), devicePathBuilder, devicePathBuilder.Capacity + 1) != 0 ?
            devicePathBuilder.ToString() :
            null;
    }

    private static string GetDriveLetter(this DriveInfo driveInfo) {
        return driveInfo.Name.Substring(0, 2);
    }

    private static string ReplaceFirst(this string text, string search, string replace) {
        int pos = text.IndexOf(search);
        if (pos < 0) {
            return text;
        }
        return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
    }
}
于 2018-01-18T11:37:48.817 回答