Haroon A.
Haroon A.

Reputation: 371

Open file location

When searching a file in Windows Explorer and right-click a file from the search results; there is an option: "Open file location". I want to implement the same in my C# WinForm. I did this:

if (File.Exists(filePath)
{
    openFileDialog1.InitialDirectory = new FileInfo(filePath).DirectoryName;
    openFileDialog1.ShowDialog();
}

Is there any better way to do it?

Upvotes: 16

Views: 54473

Answers (2)

gideon
gideon

Reputation: 19465

If openFileDialog_View is an OpenFileDialog then you'll just get a dialog prompting a user to open a file. I assume you want to actually open the location in explorer.

You would do this:

if (File.Exists(filePath))
{
    Process.Start("explorer.exe", filePath);
}

To select a file explorer.exe takes a /select argument like this:

explorer.exe /select, <filelist>

I got this from an SO post: Opening a folder in explorer and selecting a file

So your code would be:

if (File.Exists(filePath))
{
    Process.Start("explorer.exe", "/select, " + filePath);
}

Upvotes: 59

Chibueze Opata
Chibueze Opata

Reputation: 10054

This is how I do it in my code. This will open the file directory in explorer and select the specified file just the way windows explorer does it.

if (File.Exists(path))
{
    Process.Start(new ProcessStartInfo("explorer.exe", " /select, " + path);
}

Upvotes: 7

Related Questions