DevicePathMapper.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Runtime.InteropServices;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace WechatBakTool.Helpers
  9. {
  10. public static class DevicePathMapper
  11. {
  12. [DllImport("Kernel32.dll", CharSet = CharSet.Unicode)]
  13. private static extern uint QueryDosDevice([In] string lpDeviceName, [Out] StringBuilder lpTargetPath, [In] int ucchMax);
  14. public static string? FromDevicePath(string devicePath)
  15. {
  16. var drive = Array.Find(
  17. DriveInfo.GetDrives(), d =>
  18. devicePath.StartsWith(d.GetDevicePath() + "\\", StringComparison.InvariantCultureIgnoreCase)
  19. );
  20. return drive != null ?
  21. devicePath.ReplaceFirst(drive.GetDevicePath()!, drive.GetDriveLetter()) :
  22. null;
  23. }
  24. private static string? GetDevicePath(this DriveInfo driveInfo)
  25. {
  26. var devicePathBuilder = new StringBuilder(128);
  27. return QueryDosDevice(driveInfo.GetDriveLetter(), devicePathBuilder, devicePathBuilder.Capacity + 1) != 0 ?
  28. devicePathBuilder.ToString() :
  29. null;
  30. }
  31. private static string GetDriveLetter(this DriveInfo driveInfo)
  32. {
  33. return driveInfo.Name.Substring(0, 2);
  34. }
  35. private static string ReplaceFirst(this string text, string search, string replace)
  36. {
  37. int pos = text.IndexOf(search);
  38. if (pos < 0)
  39. {
  40. return text;
  41. }
  42. return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
  43. }
  44. }
  45. }