C# 打开文件夹(如果已打开则置前,而不是再打开一个新的) 并选中指定文件 shell32.dll SHOpenFolderAndSelectItems

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);

}
调用示例
完整文件路径:E:\svn\A\B\C\D\E\2020-06-29
需求:资源管理器定位至 E:\svn\A\B\C\D\E 同时选中 2020-06-29

/// <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); } }

  

  

posted @ 2020-06-29 14:53  dyfisgod  阅读(441)  评论(0编辑  收藏  举报