Opening an explorer window with designated file selected

你离开我真会死。 提交于 2019-11-27 18:08:11

问题


I have an application which has an option to show the selected file in the folder in which the file resides. My question is, how do I achieve this?

To clarify, if a user in my program selected the "Test.txt" file, then I want a Windows Explorer window to pop up and highlight the file the user selected. You can see similar behavior in LimeWire and uTorrent. If you select a file in either of those programs and choose "Show in Folder", it pops up a Windows Explorer window with the file highlighted and selected. I am trying to duplicate this behavior.

I tried using the following line:

System.Diagnostics.Process.Start("Explorer");

This will popup the Windows Explorer window, however, it always seems to open up by default in "My Documents" folder.


回答1:


Here you go,

string fileToSelect = @"C:\temp.img";
string args = string.Format("/Select, \"{0}\"", fileToSelect);

ProcessStartInfo pfi = new ProcessStartInfo("Explorer.exe", args);
System.Diagnostics.Process.Start(pfi);

Note: Adding \" before and after the {0} parameter enables the fileToSelect string to contain spaces (i.e. "C:\My Documents").

From this Thread:
Programmatically select multiple files in windows explorer

Cheers,




回答2:


There is a documented API to do this: SHOpenFolderAndSelectItems. Who knows, it might even do the right thing when explorer is not the default shell :)




回答3:


You could construct the folder path in a string, then send it to the windows command line to browse.

http://www.c-sharpcorner.com/UploadFile/DipalChoksi/ShellCommandsInCS12032005042031AM/ShellCommandsInCS.aspx




回答4:


For VB:

Dim q as Char = ControlChars.Quote
Dim path As String = q & "D:\examples\test doc.txt" & q
Dim psi as New ProcessStartInfo("Explorer.exe", "/Select, " & path)
Process.Start(psi)

As others have pointed out, paths containing spaces must be enclosed in quotes.



来源:https://stackoverflow.com/questions/3887364/opening-an-explorer-window-with-designated-file-selected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!