16

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?

Haroon A.
  • 371
  • 2
  • 7
  • 19
  • 1
    What is the problem you face with your solution? if `openFileDialog_View` is an OpenFileDialog then you'll just get a dialog prompting a user to **open** a file. – gideon Mar 10 '12 at 11:40
  • I want any alternative and better way if any? – Haroon A. Mar 10 '12 at 11:42

2 Answers2

56

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);
}
Community
  • 1
  • 1
gideon
  • 19,329
  • 11
  • 72
  • 113
  • this should be "explorer.exe" – scartag Mar 10 '12 at 11:46
  • nice Mr. gideon. but I want that file to be selected, How? – Haroon A. Mar 10 '12 at 12:14
  • 1
    @H_wardak Updated my answer. A simple [google search](http://www.google.co.in/webhp?sourceid=chrome-instant&ix=sea&ie=UTF-8&ion=1#hl=en&output=search&sclient=psy-ab&q=open%20explorer%20and%20select%20file&oq=&aq=&aqi=&aql=&gs_sm=&gs_upl=&gs_l=&pbx=1&fp=237055d012d02b32&ix=sea&ion=1&bav=on.2,or.r_gc.r_pw.r_cp.r_qf.,cf.osb&biw=1366&bih=643) landed me to that SO post. – gideon Mar 10 '12 at 12:38
7

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);
}
Chibueze Opata
  • 9,856
  • 7
  • 42
  • 65
  • 1
    is there any benefit if I using "ProcessStartInfo"? It's work without it also. – Haroon A. Mar 11 '12 at 06:20
  • Yes this opens the folder but not any apps associated with the extension. For instance if its a file.kml it might try to open google earth but sometimes you just want the file folder to open – dcarl661 Oct 29 '21 at 21:05