[Code] Show a file in Explorer

I've noticed that some of my favorite programs have options to open the currently selected file in Explorer. I don't just mean that they open the right folder, but that they preselect the right file for you.

Visual Studio 2005 does it when you select "Open Containing Folder in the File tabs:

Firefox has it in the downloaded file dialog, and TimeSnapper shows it as an option in image browse mode.

It's not hard to add to your programs, too:

Open File In Explorer

The code's reasonably simple once you've got the right arguments to pass to Explorer:

private static void ShowFileInExplorer(string filePath)
{
if (!File.Exists(filePath))
throw new FileNotFoundException("File not found", filePath);
ProcessStartInfo processStartInfo
= new ProcessStartInfo();
processStartInfo.FileName
= "explorer";
processStartInfo.UseShellExecute
= true;
processStartInfo.WindowStyle
= ProcessWindowStyle.Normal;
processStartInfo.Arguments
=
string.Format("/e,/select,\"{0}\"", filePath);
Process.Start(processStartInfo);
}

5 Comments

  • The problem with this is you are assuming that everybody uses Explorer as their shell.

    I think the best bet would be to simply launch the path and let Windows decide which application should deal with it - thus preserving the user's choice.

    [)amien

  • @Damien - Oops! We'd better tell the Visual Studio team, and the Firefox team, and...

    I get your point, but the problem with just launching the path is that Explorer just opens the folder and makes the user dig around for the file. I don't have any hard numbers, but I'm guessing the percentage of Windows users that use and alternate shell is
    (1) statistically insignificant - a fraction of a percent
    (2) technically savvy enough to find a file in their chosen shell without my help

    So as long as there's an option to copy the path and explicitly open the file in Explorer, we'd probably do the most good for the most people.

  • I am telling Scott Hanselman that you just
    1) called him statistically insignificant
    2) refused to help him.

  • I'm calling your bluff, Joe! Go ahead and turn me in.

    I don't think Scott will be surprised to hear that he's a statistical anomaly, and I don't think hearing that I'm not going to help him find files on his hard drive is going to keep him up at nights.

  • This is really handy; I've been tinkering with the process start arguments for a while, but this:

    processStartInfo.Arguments =
    string.Format("/e,/select,\"{0}\"", filePath);

    I would never have figured out. Thanks!!!

Comments have been disabled for this content.