在做一些导入导出功能时,一个打开文件所在目录并选中的功能是很人性化的。

代码如下:

/// <summary>
/// 打开路径并定位文件...对于@"h:\Bleacher Report - Hardaway with the safe call ??.mp4"这样的,explorer.exe /select,d:xxx不认,用API整它
/// </summary>
/// <param name="filePath">文件绝对路径</param>
[DllImport("shell32.dll", ExactSpelling = true)]
private static extern void ILFree(IntPtr pidlList);

[DllImport("shell32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
private static extern IntPtr ILCreateFromPathW(string pszPath);

[DllImport("shell32.dll", ExactSpelling = true)]
private static extern int SHOpenFolderAndSelectItems(IntPtr pidlList, uint cild, IntPtr children, uint dwFlags);

public void ExplorerFile(string filePath)
{
if (!File.Exists(filePath) && !Directory.Exists(filePath))
return;

if (Directory.Exists(filePath))
Process.Start(@"explorer.exe", "/select,\"" + filePath + "\"");
else
{
IntPtr pidlList = ILCreateFromPathW(filePath);
if (pidlList != IntPtr.Zero)
{
try
{
Marshal.ThrowExceptionForHR(SHOpenFolderAndSelectItems(pidlList, 0, IntPtr.Zero, 0));
}
finally
{
ILFree(pidlList);
}
}
}
}

调用如下:

if (File.Exists(path))
{
ExplorerFile(path);
}

path是包含文件名的完整文件路径。