Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
191 views
Welcome To Ask or Share your Answers For Others

1 Answer

EDIT: Newer, simpler answer.

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

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".

EDIT: Original, complicated answer:

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);
    }
}

That opens test.txt in Notepad.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...