Open a file in its default editor in C#

Viewed 116

In C#, I want to open a file in its default editor. That is, I want to do what would happen if the user opened the folder containing the file and manually opened the file for editing. Specifically:

  1. If I right-click the file in Explorer, and there is an "edit" entry in the right-click dialog, it opens the file in that editor,
  2. If there is no edit entry, it uses the app that would be used if the file is double-clicked, if that app supports editing,
  3. If there is no association with an editor, allows the user to choose a program using the same "How do you want to open this file?" dialog as when double-clicking in Explorer with no association (i.e., right click, Open With > Choose another app),
  4. Otherwise, opens in an explicitly-given fallback (e.g., notepad).

This should also be as cross-platform as possible (as cross platform as something like Process.Start is, anyway), so no registry hacks or p/Invokes. Not to mention that Process.Start seems to call into the same native APIs I would p/Invoke into, so whatever ShellExecuteEx is doing, it must not satisfy the above.

Additionally, if the file doesn't exist, something reasonable should happen. Not, for example, opening the current user's documents folder, as the example below will do.

The following solution is NOT correct:

ProcessStartInfo psi = new ProcessStartInfo(file)
{
    UseShellExecute = true
};

psi.Verb = "edit";
Process p = Process.Start(psi);

As there are some situations where this does not use the same editor as would be used by Explorer. (I don't know exactly why this happens, and the documentation seems to imply it shouldn't, but I have seen situations where it happens.)

Additionally, it doesn't seem to satisfy #3.

The following is also NOT correct:

ProcessStartInfo psi = new ProcessStartInfo("explorer")
{
    Argument = file,
};

Process p = Process.Start(psi);

As this satisfies 2 (at least sometimes?) and 3, it does not satisfy 1. For example, if I try to open a "foo.js", explorer attempts to use Windows Script Host, not an editor, even though there is an 'edit' entry in the context menu.

For posterity, the following solution obviously does not meet my requirements and seems to rely on undocumented behavior:

Process.Start("rundll32.exe shell32.dll,OpenAs_RunDLL file")
0 Answers
Related