打开文件所在位置

Har*_* A. 12 c# file winforms

在Windows资源管理器中搜索文件并右键单击搜索结果中的文件时; 有一个选项:"打开文件位置".我想在我的C#WinForm中实现相同的功能.我这样做了:

if (File.Exists(filePath)
{
    openFileDialog1.InitialDirectory = new FileInfo(filePath).DirectoryName;
    openFileDialog1.ShowDialog();
}
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法呢?

gid*_*eon 42

如果openFileDialog_ViewOpenFileDialog,那么您将获得一个提示用户打开文件的对话框.我假设您要在资源管理器中实际打开该位置.

你会这样做:

if (File.Exists(filePath))
{
    Process.Start("explorer.exe", filePath);
}
Run Code Online (Sandbox Code Playgroud)

选择一个文件explorer.exe需要一个/select像这样的说法:

explorer.exe /select, <filelist>
Run Code Online (Sandbox Code Playgroud)

我从SO帖子中得到了这个:在资源管理器中打开一个文件夹并选择一个文件

所以你的代码是:

if (File.Exists(filePath))
{
    Process.Start("explorer.exe", "/select, " + filePath);
}
Run Code Online (Sandbox Code Playgroud)


Chi*_*ata 6

这就是我在代码中的做法.这将打开资源管理器中的文件目录,并按照Windows资源管理器的方式选择指定的文件.

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