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.
With File Explorer open, tap or click the File option at the top of the window and choose Change folder and search options. Once the Folder Options window opens, tap or click the dropdown box for Open File Explorer to and make your choice. Hit OK to save it.
You can also launch File Explorer using the Run command dialog box. Here's how: Press Win + R to open the Run command dialog box. Type Explorer and then click OK to access the Windows File Explorer.
To launch File Explorer this way, press Ctrl+Shift+Esc to open Task Manager. Then, click “File” and select “Run New Task.” The “Create New Task” window will appear. Type “Explorer” in the “Open:” text box, click “OK,” and File Explorer will open.
By default, File Explorer opens to Quick Access. If you'd rather have File Explorer open to This PC, go to the View tab and then select Options. In the Open File Explorer to list, select This PC, and then select Apply.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With