【C#】在Windows资源管理器打开文件夹,并选中指定的文件或文件夹

  • 【C#】在Windows资源管理器打开文件夹,并选中指定的文件或文件夹已关闭评论
  • 165 次浏览
  • A+
所属分类:.NET技术
摘要

因软件里使用了第三方插件,第三方插件的日志文件夹存在路径不止一个,并且可能层级较深。

因软件里使用了第三方插件,第三方插件的日志文件夹存在路径不止一个,并且可能层级较深。

为便于运维人员和最终用户使用,在界面上增加一个“打开XX文件夹”的按钮,点击时,打开第三方插件日志文件夹所在的上级文件夹,并选中其下级指定名称的若干个文件和文件夹。

原本已有选中单个文件的用法,现在要的是选中多个文件的用法,较选中单个的复杂。

先看选中多个的:

函数定义:

【C#】在Windows资源管理器打开文件夹,并选中指定的文件或文件夹【C#】在Windows资源管理器打开文件夹,并选中指定的文件或文件夹

namespace MyNameSpace {     public class FileHelper     {         [DllImport("shell32.dll", ExactSpelling = true)]         public static extern int SHOpenFolderAndSelectItems(IntPtr pidlFolder, uint cidl, [In, MarshalAs(UnmanagedType.LPArray)] IntPtr[] apidl, uint dwFlags);          [DllImport("shell32.dll", CharSet = CharSet.Auto)]         public static extern IntPtr ILCreateFromPath([MarshalAs(UnmanagedType.LPTStr)] string pszPath);     }          /// <summary>         /// 在Windows资源管理器打开文件夹,并选中指定的文件或文件夹         /// </summary>         /// <param name="folderPath">文件夹路径</param>         /// <param name="filesToSelect">要选中的文件或文件夹路径</param>         public static void OpenFolderAndSelectFiles(string folderPath, params string[] filesToSelect)         {             IntPtr dir = ILCreateFromPath(folderPath);              var filesToSelectIntPtrs = new IntPtr[filesToSelect.Length];             for (int i = 0; i < filesToSelect.Length; i++)             {                 filesToSelectIntPtrs[i] = ILCreateFromPath(filesToSelect[i]);             }              SHOpenFolderAndSelectItems(dir, (uint)filesToSelect.Length, filesToSelectIntPtrs, 0);             ReleaseComObject(dir);             ReleaseComObject(filesToSelectIntPtrs);         } }

View Code

调用:

FileHelper.OpenFolderAndSelectFiles(@"D:testApp", new string[] { @"D:testAppsomefilderlog1", @"D:testAppsomefilderlog2" });

 

选中的对象支持文件和文件夹混合使用。

以上内容参考资料:

https://stackoverflow.com/questions/9355/programmatically-select-multiple-files-in-windows-explorer

 

顺便贴一下选中单个文件的用法:

【C#】在Windows资源管理器打开文件夹,并选中指定的文件或文件夹【C#】在Windows资源管理器打开文件夹,并选中指定的文件或文件夹

namespace MyNamespace {         /// <summary>         /// 按窗口句柄置顶窗口         /// </summary>         /// <param name="hwnd">窗口句柄</param>         [DllImport("user32.dll", EntryPoint = "SetForegroundWindow", SetLastError = true)]         internal static extern void SetForegroundWindow(IntPtr hwnd);          public static void ExploreFile(string filePath)         {             if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath))             {                 return;             }              //打开资源管理器并选中文件             Process process = new Process();             process.StartInfo.FileName = "explorer";             process.StartInfo.Arguments = @"/select, " + filePath;             process.Start();             SetForegroundWindow(process.MainWindowHandle);//置顶一下         }     } }

View Code