1. 程式人生 > 其它 >.NET C#模仿Windows方式開啟指定檔案所在的資料夾,並定位到檔案【加強版】

.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是指定檔案在作業系統的全路徑地址