如何打开使用shell的默认处理程序的文件?文件、程序、shell

2023-09-03 00:03:34 作者:大概是他喜欢外而我姓李

我们的客户(WinForms应用程序),包括一个文件浏览器。我希望用户能够打开使用shell的默认处理程序选定的文件。我怎么做?我读过,我应该使用Win32 API,而不是注册表,但我preFER一个解决方案,只涉及.NET。

Our client (a winforms app) includes a file-browser. I'd like the user to be able to open the selected file using the shell's default handler. How do I do that? I've read that I should use the Win32 API rather than the registry, but I'd prefer a solution that involves only .NET.

推荐答案

编辑:较新的,更简单的答案

Newer, simpler answer.

您确实可以只使用的Process.Start(文件名)。这是为的Process.Start

You can indeed just use Process.Start(filename). This is specified in the docs for Process.Start:

指定启动进程的   文件名是类似于键入   在运行对话框中的信息   Windows的开始菜单。因此,该   文件名不需要重新present   可执行文件。它可以是任何   文件类型,且该扩展具有   与应用程序被相关   安装在系统上。例如   文件名可以有一个.TXT   分机,如果您有相关的文字   通过编辑器文件,如记事本,   或者它可以有一个.doc,如果你有   用一句话associated.doc文件   加工工具,如微软   字。同样,在同样的方式,   在运行对话框中可以接受   具有或不具有可执行文件名称   .exe扩展,扩展名为.exe   是可选的文件名参数。   例如,您可以设置文件名   参数设置为Notepad.exe的或   记事本。

Starting a process by specifying its file name is similar to typing the information in the Run dialog box of the Windows Start menu. Therefore, the file name does not need to represent an executable file. It can be of any file type for which the extension has been associated with an application installed on the system. For example the file name can have a .txt extension if you have associated text files with an editor, such as Notepad, or it can have a .doc if you have associated.doc files with a word processing tool, such as Microsoft Word. Similarly, in the same way that the Run dialog box can accept an executable file name with or without the .exe extension, the .exe extension is optional in the fileName parameter. For example, you can set the fileName parameter to either "Notepad.exe" or "Notepad".

编辑:原来,复杂的答案:

Original, complicated answer:

如果您使用的Process.Start 与文件的可执行文件,并指定 UseShellExecute = TRUE 它会只是工作。例如:

If you use Process.Start with the file as the "executable" and specify UseShellExecute = true it will just work. For example:

using System;
using System.Diagnostics;

class Test
{
    static void Main()
    {
        ProcessStartInfo psi = new ProcessStartInfo("test.txt");
        psi.UseShellExecute = true;
        Process.Start(psi);
    }
}

在记事本中打开test.txt的。

That opens test.txt in Notepad.

其实, UseShellExecute = TRUE 是默认的,但它肯定需要我想明确地指定它做的更清楚给读者。

In fact, UseShellExecute=true is the default, but as it's definitely required I like to specify it explicitly to make that clearer to the reader.

 
精彩推荐
图片推荐