ExplorerAPI.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. //************************************************************************
  2. // author: yuzhengyang
  3. // date: 2018.4.27 - 2018.4.27
  4. // desc: Explorer工具类
  5. // Copyright (c) yuzhengyang. All rights reserved.
  6. // Quote: https://www.cnblogs.com/crwy/p/SHOpenFolderAndSelectItems.html
  7. //************************************************************************
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Diagnostics;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Runtime.InteropServices;
  14. using System.Text;
  15. namespace Azylee.Core.WindowsUtils.APIUtils
  16. {
  17. public class ExplorerAPI
  18. {
  19. /// <summary>
  20. /// 打开文件夹
  21. /// </summary>
  22. /// <param name="path"></param>
  23. /// <returns></returns>
  24. public static bool Open(string path)
  25. {
  26. try
  27. {
  28. if (Directory.Exists(path))
  29. {
  30. Process.Start(@"explorer.exe", "/select,\"" + path + "\"");
  31. return true;
  32. }
  33. }
  34. catch { }
  35. return false;
  36. }
  37. /// <summary>
  38. /// 打开路径并定位文件...
  39. /// 对于@"h:\Bleacher Report - Hardaway with the safe call ??.mp4"
  40. /// 这样的,explorer.exe /select,d:xxx不认,用API整它
  41. /// </summary>
  42. /// <param name="filePath">文件绝对路径</param>
  43. [DllImport("shell32.dll", ExactSpelling = true)]
  44. private static extern void ILFree(IntPtr pidlList);
  45. [DllImport("shell32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
  46. private static extern IntPtr ILCreateFromPathW(string pszPath);
  47. [DllImport("shell32.dll", ExactSpelling = true)]
  48. private static extern int SHOpenFolderAndSelectItems(IntPtr pidlList, uint cild, IntPtr children, uint dwFlags);
  49. public static void ExplorerFile(string filePath)
  50. {
  51. if (!File.Exists(filePath) && !Directory.Exists(filePath))
  52. return;
  53. if (Directory.Exists(filePath))
  54. Process.Start(@"explorer.exe", "/select,\"" + filePath + "\"");
  55. else
  56. {
  57. IntPtr pidlList = ILCreateFromPathW(filePath);
  58. if (pidlList != IntPtr.Zero)
  59. {
  60. try
  61. {
  62. Marshal.ThrowExceptionForHR(SHOpenFolderAndSelectItems(pidlList, 0, IntPtr.Zero, 0));
  63. }
  64. finally
  65. {
  66. ILFree(pidlList);
  67. }
  68. }
  69. }
  70. }
  71. }
  72. }