How do I open a file using the shell's default handler?

后端 未结 3 1896
挽巷
挽巷 2020-12-05 17:59

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 r

相关标签:
3条回答
  • 2020-12-05 18:15

    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.

    0 讨论(0)
  • 2020-12-05 18:29

    not sure if its ok

    System.Diagnostics.Process.Start(filePath);
    
    0 讨论(0)
  • 2020-12-05 18:33

    System.Diagnostics.Process provides the .Net native wrapper around shell32.ShellExecute.

    See PInvoke.Net for a discussion of both APIs, and MSDN docs on MSDN .

    0 讨论(0)
提交回复
热议问题