【C#】打开文件夹并选中文件

 

/// 
/// 打开路径并定位文件
/// 
/// 文件绝对路径
[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 static 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);
            }
        }
    }
}

 

你可能感兴趣的:(C#)