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?

2
  • 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, 2012 at 11:40
  • I want any alternative and better way if any?
    – Haroon A.
    Mar 10, 2012 at 11:42

2 Answers 2

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);
}
3
  • this should be "explorer.exe"
    – scartag
    Mar 10, 2012 at 11:46
  • nice Mr. gideon. but I want that file to be selected, How?
    – Haroon A.
    Mar 10, 2012 at 12:14
  • 1
    @H_wardak Updated my answer. A simple google search landed me to that SO post.
    – gideon
    Mar 10, 2012 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);
}
2
  • 1
    is there any benefit if I using "ProcessStartInfo"? It's work without it also.
    – Haroon A.
    Mar 11, 2012 at 6: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, 2021 at 21:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.