.NET C#模仿Windows方式打开指定文件所在的文件夹,并定位到文件【加强版】

直接上方法。

using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;

public class ExplorerFileExtensions
    {
        #region 对指定文件,打开所在的文件夹,并定位到文件
        /// <summary>
        /// 打开路径并定位文件...对于@"d:\aa\A Report - Call ??.mp3"这样的,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);
        /// <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);
                    }
                }
            }
        }
    }

调用方式,ExplorerFileExtensions.ExplorerFile(fileFullPath);其中fileFullPath是指定文件在操作系统的全路径地址

posted @ 2022-03-31 14:30  jeff151013  阅读(617)  评论(0编辑  收藏  举报