static public class Win32Helper
{
///
/// 释放命令行管理程序分配的ITEMIDLIST结构
/// Frees an ITEMIDLIST structure allocated by the Shell.
///
///
[DllImport("shell32.dll", ExactSpelling = true)]
public static extern void ILFree(IntPtr pidlList);
///
/// 返回与指定文件路径关联的ITEMIDLIST结构。
/// Returns the ITEMIDLIST structure associated with a specified file path.
///
///
///
[DllImport("shell32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
public static extern IntPtr ILCreateFromPathW(string pszPath);
///
/// 打开一个Windows资源管理器窗口,其中选择了特定文件夹中的指定项目。
/// Opens a Windows Explorer window with specified items in a particular folder selected.
///
///
///
///
///
///
[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
///
/// 打开目录并选中相应文件
///
///
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);
}
}