Opening a folder in explorer and selecting a file

Michael L picture Michael L · Dec 2, 2008 · Viewed 144.9k times · Source

I'm trying to open a folder in explorer with a file selected.

The following code produces a file not found exception:

System.Diagnostics.Process.Start(
    "explorer.exe /select," 
    + listView1.SelectedItems[0].SubItems[1].Text + "\\" 
    + listView1.SelectedItems[0].Text);

How can I get this command to execute in C#?

Answer

Samuel Yang picture Samuel Yang · Mar 30, 2009
// suppose that we have a test.txt at E:\
string filePath = @"E:\test.txt";
if (!File.Exists(filePath))
{
    return;
}

// combine the arguments together
// it doesn't matter if there is a space after ','
string argument = "/select, \"" + filePath +"\"";

System.Diagnostics.Process.Start("explorer.exe", argument);