How do I start a process from C#?
Asked Answered
F

15

201

How do I start a process, such as launching a URL when the user clicks a button?

Flunkey answered 8/10, 2008 at 7:46 Comment(0)
G
266

As suggested by Matt Hamilton, the quick approach where you have limited control over the process, is to use the static Start method on the System.Diagnostics.Process class...

using System.Diagnostics;
...
Process.Start("process.exe");

The alternative is to use an instance of the Process class. This allows much more control over the process including scheduling, the type of the window it will run in and, most usefully for me, the ability to wait for the process to finish.

using System.Diagnostics;
...
Process process = new Process();
// Configure the process using the StartInfo properties.
process.StartInfo.FileName = "process.exe";
process.StartInfo.Arguments = "-n";
process.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
process.Start();
process.WaitForExit();// Waits here for the process to exit.

This method allows far more control than I've mentioned.

Guardroom answered 8/10, 2008 at 8:42 Comment(2)
i used this method to open .msg file using outlook but when i try to open another .msg file, it opened up another outlook. is there any way to reuse the current process and avoid opening up another outlook? #28534858Heyde
You should use a using statement or dispose of the process as well #16957820Phelloderm
G
30

You can use the System.Diagnostics.Process.Start method to start a process. You can even pass a URL as a string and it'll kick off the default browser.

Gridiron answered 8/10, 2008 at 7:49 Comment(0)
P
19

Just as Matt says, use Process.Start.

You can pass a URL, or a document. They will be started by the registered application.

Example:

Process.Start("Test.Txt");

This will start Notepad.exe with Text.Txt loaded.

Pane answered 8/10, 2008 at 8:27 Comment(2)
What happens, if no program is registered for this type?Mariejeanne
@LC Win32Exception (0x80004005) "No application is associated with the specified file for this operation"Commandment
C
12

I used the following in my own program.

Process.Start("http://www.google.com/etc/etc/test.txt")

It's a bit basic, but it does the job for me.

Concertante answered 18/7, 2014 at 10:53 Comment(1)
When used with a URL as your example does, this also has the advantage of using the system's default web browser to open the URL.Indicant
J
6
var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "/YourSubDirectory/yourprogram.exe");
Process.Start(new ProcessStartInfo(path));
Jacquesjacquet answered 30/3, 2015 at 22:12 Comment(0)
A
6
class ProcessStart
{
    static void Main(string[] args)
    {
        Process notePad = new Process();

        notePad.StartInfo.FileName   = "notepad.exe";
        notePad.StartInfo.Arguments = "ProcessStart.cs";

        notePad.Start();
    }
}
Astronautics answered 26/5, 2016 at 11:35 Comment(0)
W
5

Use the Process class. The MSDN documentation has an example how to use it.

Wilbur answered 8/10, 2008 at 7:49 Comment(0)
L
5

You can use this syntax for running any application:

System.Diagnostics.Process.Start("Example.exe");

And the same one for a URL. Just write your URL between this ().

Example:

System.Diagnostics.Process.Start("http://www.google.com");
Lamontlamontagne answered 30/6, 2015 at 14:11 Comment(0)
H
5

If using on Windows

Process process = new Process();
process.StartInfo.FileName = "Test.txt";
process.Start();

Works for .Net Framework but for Net core 3.1 also need to set UseShellExecute to true

Process process = new Process();
process.StartInfo.FileName = "Test.txt";
process.StartInfo.UseShellExecute = true;
process.Start();
Hookworm answered 14/7, 2020 at 13:37 Comment(1)
using System.Diagnostics;Checkbook
O
3

Declare this

[DllImport("user32")]
private static extern bool SetForegroundWindow(IntPtr hwnd);
[DllImport("user32")]
private static extern bool ShowWindowAsync(IntPtr hwnd, int a);

And put this inside your function (note that "checkInstalled" is optional, but if you'll use it, you have to implement it)

if (ckeckInstalled("example"))
{
    int count = Process.GetProcessesByName("example").Count();
    if (count < 1)
        Process.Start("example.exe");
    else
    {
        var proc = Process.GetProcessesByName("example").FirstOrDefault();
        if (proc != null && proc.MainWindowHandle != IntPtr.Zero)
        {
            SetForegroundWindow(proc.MainWindowHandle);
            ShowWindowAsync(proc.MainWindowHandle, 3);
        }
    }
}

NOTE: I'm not sure if this works when more than one instance of the .exe is running.

Obscurantism answered 13/8, 2015 at 16:47 Comment(0)
M
2

Include the using System.Diagnostics;.

And then call this Process.Start("Paste your URL string here!");

Try something like this:

using System.Web.UI;
using System.Web.UI.WebControls;
using System.Diagnostics;

namespace btnproce
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            string t ="Balotelli";
            Process.Start("http://google.com/search?q=" + t);
        }
    }
}

Please note that it is a sample ASP.NET page as an example. You should try and improvise a little bit.

Marconigraph answered 6/11, 2014 at 5:40 Comment(0)
S
2

To start Microsoft Word for example, use this code:

private void button1_Click(object sender, EventArgs e)
{
    string ProgramName = "winword.exe";
    Process.Start(ProgramName);
}

For more explanations, check out this link.

Soothsayer answered 1/9, 2016 at 17:26 Comment(0)
R
0

You can use this syntax:

private void button1_Click(object sender, EventArgs e)  {
   System.Diagnostics.Process.Start(/*your file name goes here*/);
}

Or even this:

using System;
using System.Diagnostics;
//rest of the code

private void button1_Click(object sender, EventArgs e)  {
   Process.Start(/*your file name goes here*/);
}

Both methods would perform the same task.

Rist answered 28/3, 2021 at 16:42 Comment(0)
C
0
Process openTerminal = new Process();

openTerminal.StartInfo.FileName = "/usr/bin/osascript"; // The 'osascript' command on macOS

// AppleScript to open Terminal and execute commands
openTerminal.StartInfo.Arguments = "-e 'tell application \"Terminal\" to do script \"echo Hello World\"'";
openTerminal.StartInfo.UseShellExecute = false;
openTerminal.Start(); 

you can try this to run terminal on macOS and print Hello world

Cubic answered 14/8, 2023 at 7:24 Comment(0)
T
0

I think you can use CreateProcess from the Win32 API.

Code sample:

using System;
using System.Runtime.InteropServices;


class Demo
{
    [StructLayout(LayoutKind.Sequential)]
    struct StartupInfo
    {
        public int cb;
        public string lpReserved;
        public string lpDesktop;
        public int lpTitle;
        public int dwX;
        public int dwY;
        public int dwXSize;
        public int dwYSize;
        public int dwXCountChars;
        public int dwYCountChars;
        public int dwFillAttribute;
        public int dwFlags;
        public int wShowWindow;
        public int cbReserved2;
        public byte lpReserved2;
        public int hStdInput;
        public int hStdOutput;
        public int hStdError;
    }

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern bool CreateProcess(string lpApplicationName, string lpCommandLine, int lpProcessAttributes,
        int lpThreadAttributes, int bInheritHandles, int dwCreationFlags, int lpEnvironment,
        int lpCurrentDirectory, StartupInfo lpStartupInfo, out int lpProcessInformation);

    static void Main()
    {
        var info = new StartupInfo();
        if (!CreateProcess("C:\\Windows\\System32\\cmd.exe", "/c ping", 0, 0, 0, 0, 0, 0, info, out _))
        {
            Console.WriteLine(Marshal.GetLastWin32Error());
            Console.ReadKey();
        }
    }
}


References: CreateProcessA function (processthreadsapi.h)

Thunderhead answered 22/8, 2023 at 21:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.