code to open windows explorer (or focus if exists) with file selected
Asked Answered
M

1

20

My goal is to write a C# code that will open a Windows Explorer window, with a particular file selected. If such window is already open, I want to bring it to front. I have tried two options.

First, I start by explicitly calling explorer.exe:

arg = "/select, " + pathToFile;
Process.Start("explorer.exe", arg);

This opens and selects a window fine, but the problem is that it will always open a new window, even if one exists. So I tried this:

Process.Start(pathToDir);

This either opens a new window or focuses an old one, but gives me no option to select a file.

What can I do? I looked at explorer's arguments and I don't see anything I can use. A last-resort option I can come up with is to get the list of already open windows and use some WINAPI-level code to handle it, but that seems like an overkill.

Moody answered 30/1, 2013 at 9:51 Comment(1)
try "/select," + pathToFile (no space between the comma and path)Dubiety
B
19

I don't know if it's possible using process start, but the following code opens the Windows explorer on the containing folder only if needed (if the folder is already open, or selected on another file, it's reused) and selects the desired file.

It's using p/invoke interop code on the SHOpenFolderAndSelectItems function:

public static void OpenFolderAndSelectFile(string filePath)
{
    if (filePath == null)
        throw new ArgumentNullException("filePath");

    IntPtr pidl = ILCreateFromPathW(filePath);
    SHOpenFolderAndSelectItems(pidl, 0, IntPtr.Zero, 0);
    ILFree(pidl);
}

[DllImport("shell32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr ILCreateFromPathW(string pszPath);

[DllImport("shell32.dll")]
private static extern int SHOpenFolderAndSelectItems(IntPtr pidlFolder, int cild, IntPtr apidl, int dwFlags);

[DllImport("shell32.dll")]
private static extern void ILFree(IntPtr pidl);
Bili answered 30/1, 2013 at 10:25 Comment(1)
Nearly 10 years later and still working. +10 if I could.Ulpian

© 2022 - 2024 — McMap. All rights reserved.