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

 

/// <summary>
/// 打开路径并定位文件
/// </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);

/// <summary>
/// 打开文件夹并选中文件
/// </summary>
/// <param name="filePath"></param>
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);
            }
        }
    }
}

 

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 精致技术 设计师:CSDN官方博客 返回首页