需求:
对于完整文件路径:E:\svn\A\B\C\D\E\2020-06-29
资源管理器定位至 E:\svn\A\B\C\D\E 同时选中 2020-06-29文件夹
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | static public class Win32Helper { /// <summary> /// 释放命令行管理程序分配的ITEMIDLIST结构 /// Frees an ITEMIDLIST structure allocated by the Shell. /// </summary> /// <param name="pidlList"></param> [DllImport("shell32.dll", ExactSpelling = true)] public static extern void ILFree(IntPtr pidlList); /// <summary> /// 返回与指定文件路径关联的ITEMIDLIST结构。 /// Returns the ITEMIDLIST structure associated with a specified file path. /// </summary> /// <param name="pszPath"></param> /// <returns></returns> [DllImport("shell32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)] public static extern IntPtr ILCreateFromPathW(string pszPath); /// <summary> /// 打开一个Windows资源管理器窗口,其中选择了特定文件夹中的指定项目。 /// Opens a Windows Explorer window with specified items in a particular folder selected. /// </summary> /// <param name="pidlList"></param> /// <param name="cild"></param> /// <param name="children"></param> /// <param name="dwFlags"></param> /// <returns></returns> [DllImport("shell32.dll", ExactSpelling = true)] public static extern int SHOpenFolderAndSelectItems(IntPtr pidlList, uint cild, IntPtr children, uint dwFlags); } …… /// <summary> /// 打开目录并选中相应文件 /// </summary> /// <param name="fileFullName"></param> static public void OpenFolderAndSelectFile(string fileFullName) { if (fileFullName.IsNullOrEmpty()) throw new ArgumentNullException(nameof(fileFullName)); fileFullName = Path.GetFullPath(fileFullName); var pidlList = Win32Helper.ILCreateFromPathW(fileFullName); if (pidlList == IntPtr.Zero) return; try { Marshal.ThrowExceptionForHR(Win32Helper.SHOpenFolderAndSelectItems(pidlList, 0, IntPtr.Zero, 0)); } finally { Win32Helper.ILFree(pidlList); } } |