56

I'm looking for the .NET-preferred way of performing the same type of thing that ShellExecute does in Win32 (opening, printing, etc. for arbitrary file types).

I've been programming Windows for over 20 years, but I'm a complete newbie at .NET, so maybe I'm just looking in the wrong places. I'm currently using .NET 2.0 (VS C# 2005), but could use VS 2008 if need be.

If the only answer is to use P/Invoke, then I might be better just writing my small utility using Win32 anyway.

5 Answers 5

73

Process.Start.

Note that advanced uses (printing etc) require using a ProcessStartInfo and setting the Verb property.

1
  • 14
    (There is a bool property 'UseShellExecute' on it.) Commented Aug 24, 2010 at 21:34
44
System.Diagnostics.Process.Start(command)

I bet you had trouble finding it because it is in the System.Diagnostics namespace. "Diagnostics"? Usually with 20 years experience one thing you get good at is guessing at what something will be called in a new API/language, but this one tricked me.

3
  • This only works if command is a single path to an executable, URL, or a filename with a registered Open command. This won't work: System.Diagnostics.Process.Start("notepad foo.txt") Commented May 17 at 13:12
  • This works though: Process.Start("notepad.exe",@"c:\windows\system32\drivers\etc\hosts"); Commented May 17 at 13:14
  • And this, for when code.cmd is in your path: Process.Start(@"cmd.exe", $" /c code \"{filename}\""); Commented May 17 at 13:20
4

Have you tried System.Diagnostics.Process.Start()?

It's more or less similar to ShellExecute. You can open exes, documents. I haven't checked printing yet, Marc has told you how already.

1

Here are the original Win32 ShellExecute() docs: https://learn.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-shellexecutea

This C# code will work to open a web browser tab for a URL:

ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "https://www.google.com/";
psi.UseShellExecute = true;
psi.WindowStyle = ProcessWindowStyle.Normal;
Process.Start(psi);
1
  • This only works if command is a single path to an executable, URL, or a filename with a registered Open command. This won't work: System.Diagnostics.Process.Start("notepad foo.txt") Commented May 17 at 13:12
0
System.Diagnostics.Process.Start("explorer.exe", path);
1
  • This only works if command is a single path to an executable, URL, or a filename with a registered Open command. This won't work: System.Diagnostics.Process.Start("notepad foo.txt") Commented May 17 at 13:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.