2
0

DevicePathMapper.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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 WechatPCMsgBakTool.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(DriveInfo.GetDrives(), d => devicePath.StartsWith(d.GetDevicePath(), StringComparison.InvariantCultureIgnoreCase));
  17. return drive != null ?
  18. devicePath.ReplaceFirst(drive.GetDevicePath(), drive.GetDriveLetter()) :
  19. null;
  20. }
  21. private static string GetDevicePath(this DriveInfo driveInfo)
  22. {
  23. var devicePathBuilder = new StringBuilder(128);
  24. return QueryDosDevice(driveInfo.GetDriveLetter(), devicePathBuilder, devicePathBuilder.Capacity + 1) != 0 ?
  25. devicePathBuilder.ToString() :
  26. null;
  27. }
  28. private static string GetDriveLetter(this DriveInfo driveInfo)
  29. {
  30. return driveInfo.Name.Substring(0, 2);
  31. }
  32. private static string ReplaceFirst(this string text, string search, string replace)
  33. {
  34. int pos = text.IndexOf(search);
  35. if (pos < 0)
  36. {
  37. return text;
  38. }
  39. return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
  40. }
  41. }
  42. }