Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

C:\FOLDER\SUBFOLDER\FILE.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?

like image 890
Jester Avatar asked Dec 03 '12 09:12

Jester


People also ask

How do I get File Explorer to open in a specific folder?

To open Windows File Explorer to a specific folder, create a shortcut to “%SYSTEMROOT%\explorer.exe /e,<folder>”, where “<folder>” is the folder of your choice.

How do I open a specific file path?

Navigate to the location of your file by typing the following into the command prompt window: Users\”Username”> cd C:\”Users\”Username”\”Location” In this example, the “Username” will be User and the “Location” will be desktop. Then type in the name and extension of the file you're trying to open: “Filename.

How do I open a specific path in Windows?

Click the Start button and then click Computer, click to open the location of the desired folder, and then right-click to the right of the path in the address bar.

How do I change the default File Explorer?

It is available for free on the Microsoft Store. Next, open Files and press the gear icon in the top right corner. This will open up the settings menu. In the left sidebar, go to Experimental, and under Default file explorer toggle the Set Files as default file explorer on.


1 Answers

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.

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

like image 63
Mahmoud Al-Qudsi Avatar answered Sep 28 '22 02:09

Mahmoud Al-Qudsi