C# 打开文件所在位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9646114/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 08:17:59  来源:igfitidea点击:

Open file location

c#winformsfile

提问by Haroon A.

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:

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

if (File.Exists(filePath)
{
    openFileDialog1.InitialDirectory = new FileInfo(filePath).DirectoryName;
    openFileDialog1.ShowDialog();
}

Is there any better way to do it?

有没有更好的方法来做到这一点?

采纳答案by gideon

If openFileDialog_Viewis an OpenFileDialogthen you'll just get a dialog prompting a user to open a file. I assume you want to actually openthe location in explorer.

如果openFileDialog_ViewOpenFileDialog,那么您只会得到一个对话框,提示用户打开文件。我假设您想在资源管理器中实际打开该位置。

You would do this:

你会这样做:

if (File.Exists(filePath))
{
    Process.Start("explorer.exe", filePath);
}


To selecta file explorer.exetakes a /selectargument like this:

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

explorer.exe /select, <filelist>

I got this from an SO post: Opening a folder in explorer and selecting a file

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

So your code would be:

所以你的代码是:

if (File.Exists(filePath))
{
    Process.Start("explorer.exe", "/select, " + filePath);
}

回答by Chibueze Opata

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.

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

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