Open a folder in Windows Explorer and select a file works second time only
Asked Answered
H

2

9

Using the code described in this answer of the SO posting "Open folder and select the file", I've created this function:

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

This function works well, with one small issue:

Calling the function for the first time for a specific file, Windows Explorer is correctly shown with the folder of the file, but it does not select the file.

Calling the same function again for the same file, it switches back to the already open folder in Windows Explorer and then it selects the file.

E.g. the first call to OpenExplorerAndSelectFile("C:\MyFolder\MyFile.txt") opens the folder "C:\MyFolder" in a new Windows Explorer Window. The second call to OpenExplorerAndSelectFile("C:\MyFolder\MyFile.txt") actually activates that Window again and selects MyFile.txt.

Doing something similar in e.g. Google Chrome (Going to the download page and showing a previously downloaded file) actually works well right in the first try.

So my conclusion is that Google Chrome seems to do it a bit different than I do.

My question:

Is there a way to debug/trace the Win32/Shell method that Google Chrome calls?

I would then compare them to what I do to see the differences.

Hydrothermal answered 22/3, 2014 at 14:20 Comment(3)
I can't reproduce this on Win7/x64. For me it selects the file on the first time, but it doesn't re-use the open window, it always creates a new oneElection
SHOpenFolderAndSelectItems : #1073853Survive
@AlexK. This works perfectly, thanks a lot! Maybe you can put this as an answer so I can accept it?Hydrothermal
S
2

Rather than the explorer command line Chrome most probably uses the more flexible SHOpenFolderAndSelectItems Shell API.

This answer contains the required p/invoke/implementation.

Survive answered 24/3, 2014 at 11:37 Comment(1)
Still, this solution doesn't work for me if performed on a newly created / renamed / copied folder. Can someone please verify?Valentinevalentino
M
-3

Try using the shell function "SHOpenFolderAndSelectItems".

Malchus answered 23/3, 2014 at 5:5 Comment(1)
So you basically copied the comment of Alex K.?Hydrothermal

© 2022 - 2024 — McMap. All rights reserved.