Created
February 22, 2019 06:48
-
-
Save jymcheong/6191fcfc37926e293d32c97eed58d136 to your computer and use it in GitHub Desktop.
C# DevicePathMapper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
string fullpath = DevicePathMapper.FromDevicePath((string)data.PayloadByName("ImageName"));