Create Process Examples in .NET (C# and VB.NET)
Create a new process in .NET with a simple Process.Start("notepad.exe")
but more control is had by creating a Process
object. Process.Start("http://www.bing.com")
also works. Probably, Process.Start()
is using the WinAPI ShellExecute()
function while the Process
object is using the CreateProcess()
function.
Imports System.Diagnostics
Module Module1
Sub Main()
Dim pro As New Process()
pro.StartInfo.FileName = "notepad.exe"
pro.StartInfo.Arguments = "temp.txt"
'can specify ProcessWindowStyle.Hidden for programs that do not need user input
pro.StartInfo.WindowStyle = ProcessWindowStyle.Normal
pro.Start()
pro.WaitForExit()
End Sub
End Module
C#:
using System.Diagnostics;
namespace Console1
{
class Program
{
static void Main(string[] args)
{
Process pro = new Process();
pro.StartInfo.FileName = "notepad.exe";
pro.StartInfo.Arguments = "temp.txt";
//can specify ProcessWindowStyle.Hidden for programs that do not need user input
pro.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
pro.Start();
pro.WaitForExit();
}
}
}
Create a console process and read its output.
using (var proc = new System.Diagnostics.Process
{
StartInfo = new System.Diagnostics.ProcessStartInfo
{
FileName = "/bin/executable.exe",
Arguments = "-arguments",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
})
{
proc.Start();
while (!proc.StandardOutput.EndOfStream)
{
string line = proc.StandardOutput.ReadLine();
// do something with this line of text
}
}
Now, read binary data from a console process.
using (var proc = new System.Diagnostics.Process
{
StartInfo = new System.Diagnostics.ProcessStartInfo
{
FileName = "/bin/executable.exe",
Arguments = "-arguments",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
})
{
proc.Start();
using (BinaryReader reader = new BinaryReader(proc.StandardOutput.BaseStream))
{
byte[] chunk = reader.ReadBytes(1024);
while (chunk.Length > 0)
{
// do something with this byte array
chunk = reader.ReadBytes(1024);
}
}
}