Jester Jester - 1 month ago 17x
C# Question

How to open Explorer with a specific file selected?

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


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?


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:\Folder\subfolder\file.txt"

will open a new explorer window to C:\Folder\subfolder with file.txt selected.

Building off Tigran's example (error checking omitted):

public void OpenFolder(string filePath) {
    Process.Start("explorer.exe", string.Format("/select,\"{0}\"", filePath));

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.