Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

C:FOLDERSUBFOLDERFILE.TXT

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.)

How can I do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
152 views
Welcome To Ask or Share your Answers For Others

1 Answer

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"

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

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.

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;
}

Reference: Explorer.exe Command-line switches


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...