ExplorerAPI.cs 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. /// </summary>
  40. /// <param name="filePath"></param>
  41. public static void OpenFile(string filePath)
  42. {
  43. ExplorerFile(filePath);
  44. }
  45. /// <summary>
  46. /// 打开路径并定位文件...
  47. /// 对于@"h:\Bleacher Report - Hardaway with the safe call ??.mp4"
  48. /// 这样的,explorer.exe /select,d:xxx不认,用API整它
  49. /// </summary>
  50. /// <param name="filePath">文件绝对路径</param>
  51. [DllImport("shell32.dll", ExactSpelling = true)]
  52. private static extern void ILFree(IntPtr pidlList);
  53. [DllImport("shell32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
  54. private static extern IntPtr ILCreateFromPathW(string pszPath);
  55. [DllImport("shell32.dll", ExactSpelling = true)]
  56. private static extern int SHOpenFolderAndSelectItems(IntPtr pidlList, uint cild, IntPtr children, uint dwFlags);
  57. public static void ExplorerFile(string filePath)
  58. {
  59. try
  60. {
  61. if (!File.Exists(filePath) && !Directory.Exists(filePath))
  62. return;
  63. if (Directory.Exists(filePath))
  64. Process.Start(@"explorer.exe", "/select,\"" + filePath + "\"");
  65. else
  66. {
  67. IntPtr pidlList = ILCreateFromPathW(filePath);
  68. if (pidlList != IntPtr.Zero)
  69. {
  70. try
  71. {
  72. Marshal.ThrowExceptionForHR(SHOpenFolderAndSelectItems(pidlList, 0, IntPtr.Zero, 0));
  73. }
  74. finally
  75. {
  76. ILFree(pidlList);
  77. }
  78. }
  79. }
  80. }
  81. catch { }
  82. }
  83. }
  84. }