C# 打开目录,且同一目录不重复打开新窗口
针对同一目录不重复打开新窗口
两种方法:
第一种,仅打开目录
1 static public class Win32Help 2 { 3 public enum ShowCommands : int 4 { 5 SW_HIDE = 0, 6 SW_SHOWNORMAL = 1, 7 SW_NORMAL = 1, 8 SW_SHOWMINIMIZED = 2, 9 SW_SHOWMAXIMIZED = 3, 10 SW_MAXIMIZE = 3, 11 SW_SHOWNOACTIVATE = 4, 12 SW_SHOW = 5, 13 SW_MINIMIZE = 6, 14 SW_SHOWMINNOACTIVE = 7, 15 SW_SHOWNA = 8, 16 SW_RESTORE = 9, 17 SW_SHOWDEFAULT = 10, 18 SW_FORCEMINIMIZE = 11, 19 SW_MAX = 11 20 } 21 22 [DllImport("shell32.dll")] 23 public static extern IntPtr ShellExecute(IntPtr hwnd, string lpOperation, string lpFile, string lpParameters, string lpDirectory, ShowCommands nShowCmd); 24 } 25 26 //调用 27 28 static public void OpenFolder(string fileFullName) => Win32Help.ShellExecute(IntPtr.Zero, "open", fileFullName, "", "", Win32Help.ShowCommands.SW_SHOWNORMAL);
第二种,打开目录并选中指定文件
[DllImport("shell32.dll", ExactSpelling = true)] public static extern void ILFree(IntPtr pidlList); [DllImport("shell32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)] public static extern IntPtr ILCreateFromPathW(string pszPath); [DllImport("shell32.dll", ExactSpelling = true)] public static extern int SHOpenFolderAndSelectItems(IntPtr pidlList, uint cild, IntPtr children, uint dwFlags); /// <summary> /// 打开指定文件夹并选中相应文件 /// </summary> /// <param name="fileFullName">目录或文件路径</param> /// <returns></returns> internal static bool SelectInFileExplorer(this string fileFullName) { if (fileFullName.IsNullOrEmpty()) throw new ArgumentNullException(nameof(fileFullName)); fileFullName = System.IO.Path.GetFullPath(fileFullName); var pidlList = Win32Help.ILCreateFromPathW(fileFullName); if (pidlList == IntPtr.Zero) return false; try { Marshal.ThrowExceptionForHR(Win32Help.SHOpenFolderAndSelectItems(pidlList, 0, IntPtr.Zero, 0)); return true; } catch (Exception e) { return false; } finally { Win32Help.ILFree(pidlList); } } //调用 /// <summary> /// 打开目录并选中相应文件 /// </summary> /// <param name="fileFullName"></param> static public void OpenFolderAndSelectFile(string fileFullName) => Win32Help.SelectInFileExplorer(fileFullName);