如何使用选定的特定文件打开资源管理器? [英] How to open Explorer with a specific file selected?

查看:30
本文介绍了如何使用选定的特定文件打开资源管理器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个可以传递文件路径的函数,例如:

I would like to code a function to which you can pass a file path, for example:

C:FOLDERSUBFOLDERFILE.TXT

它会用包含文件的文件夹打开 Windows 资源管理器,然后在文件夹中选择这个文件.(类似于许多程序中使用的在文件夹中显示"概念.)

and it would open Windows Explorer with the folder containing the file and then select this file inside the folder. (Similar to the "Show In Folder" concept used in many programs.)

我该怎么做?

推荐答案

不使用 Win32 shell 函数的最简单方法是使用 /select 参数简单地启动 explorer.exe.例如启动进程

Easiest way without using Win32 shell functions is to simply launch explorer.exe with the /select parameter. For example, launching the process

explorer.exe/select,"C:Foldersubfolderfile.txt"

将打开一个新的资源管理器窗口到 C:Foldersubfolder 并选择 file.txt.

will open a new explorer window to C:Foldersubfolder with file.txt selected.

如果您希望在不启动新进程的情况下以编程方式执行此操作,则需要使用 shell 函数 SHOpenFolderAndSelectItems,这是explorer.exe的/select命令内部使用.请注意,这需要使用 PIDL,如果您不熟悉 shell API 的工作原理,则可以成为真正的 PITA.

If you wish to do it programmatically without launching a new process, you'll need to use the shell function SHOpenFolderAndSelectItems, which is what the /select command to explorer.exe will use internally. Note that this requires the use of PIDLs, and can be a real PITA if you are not familiar with how the shell APIs work.

这是 /select 方法的一个完整的、程序化的实现,在@Bhushan 和@tehDorf 的建议下进行了路径清理:

Here's a complete, programmatic implementation of the /select approach, with path cleanup thanks to suggestions from @Bhushan and @tehDorf:

public bool ExploreFile(string filePath) {
    if (!System.IO.File.Exists(filePath)) {
        return false;
    }
    //Clean up file path so it can be navigated OK
    filePath = System.IO.Path.GetFullPath(filePath);
    System.Diagnostics.Process.Start("explorer.exe", string.Format("/select,"{0}"", filePath));
    return true;
}

参考:Explorer.exe 命令行开关

这篇关于如何使用选定的特定文件打开资源管理器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆