Friday, March 4, 2011

C#, Open Folder and Select the file

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#?

From stackoverflow
  • You need to put the arguments to pass ("/select etc") in the second parameter of the Start method.

  • Use this method:

    http://msdn.microsoft.com/en-us/library/h6ak8zt5.aspx

    Process.Start(String, String)

    First argument is an application (explorer.exe), second method argument are arguments of the application you run.

    For example:

    in CMD: explorer.exe -p

    in C#: Process.Start("explorer.exe", "-p")

    Michael L : Thanks Tomaszs, it worked!
  • Use "/select,c:\file.txt"

    Notice there should be a comma after /select instead of space..

  •         // 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);
    
  • Just my 2 cents worth, if your filename contains spaces, ie "c:\My File Contains Spaces.txt", you'll need to surround the filename with quotes otherwise explorer will assume that the othe words are different arguments...

    string argument = "/select, \"" + filePath +"\"";
    
  • Thanks Adrian : works very well !

0 comments:

Post a Comment