Running OS commands
suggest changeIn .NET, executing operating system commands and external binaries is handled by the System.Diagnostics.Process class paired with ProcessStartInfo.
1. Basic Command Execution with Process.Start
To run an external executable, configure a ProcessStartInfo instance with the filename, arguments, and execution settings:
using System;
using System.Diagnostics;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
var psi = new ProcessStartInfo
{
FileName = "git",
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
};
// Modern .NET recommendation: use ArgumentList to prevent command injection
psi.ArgumentList.Add("status");
psi.ArgumentList.Add("--short");
using var process = new Process { StartInfo = psi };
process.Start();
// Read both streams concurrently to avoid a pipe-buffer deadlock
Task<string> stdoutTask = process.StandardOutput.ReadToEndAsync();
Task<string> stderrTask = process.StandardError.ReadToEndAsync();
await process.WaitForExitAsync();
string stdout = await stdoutTask;
string stderr = await stderrTask;
Console.WriteLine($"Exit code: {process.ExitCode}");
Console.WriteLine($"Output:\n{stdout}");
if (!string.IsNullOrWhiteSpace(stderr))
{
Console.Error.WriteLine($"Error:\n{stderr}");
}
}
}
2. Preventing Command Injection with ArgumentList
In older .NET Framework versions, developers concatenated arguments into a single string:
// VULNERABLE to injection if userInput contains quotes, semicolons, or pipes!
psi.Arguments = "commit -m \"" + userInput + "\"";
In modern .NET (.NET Core 2.1+), always use the ArgumentList collection. The runtime automatically quotes and escapes individual arguments according to the host operating system's command-line conventions:
var psi = new ProcessStartInfo("git")
{
UseShellExecute = false
};
// Safe against argument injection
psi.ArgumentList.Add("commit");
psi.ArgumentList.Add("-m");
psi.ArgumentList.Add(userInput); // Passed safely without manual escaping
3. Streaming Real-Time Output
For long-running tools (like build scripts, compilers, or test runners), buffer-filling methods like ReadToEndAsync() will block until the process finishes. Use asynchronous event handlers to stream output in real time:
using System;
using System.Diagnostics;
var psi = new ProcessStartInfo
{
FileName = "dotnet",
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
};
psi.ArgumentList.Add("test");
using var process = new Process { StartInfo = psi };
// Register event handlers
process.OutputDataReceived += (sender, args) =>
{
if (args.Data != null)
{
Console.WriteLine($"[STDOUT] {args.Data}");
}
};
process.ErrorDataReceived += (sender, args) =>
{
if (args.Data != null)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"[STDERR] {args.Data}");
Console.ResetColor();
}
};
process.Start();
// Begin asynchronous read loops
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
Console.WriteLine($"Process completed with code: {process.ExitCode}");
4. Running Shell Built-ins Across Operating Systems
Commands like dir, echo, ls, or shell pipes (|) are internal features of the command shell rather than standalone binaries. To execute shell built-ins, invoke the platform-specific shell:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
ProcessStartInfo CreateShellProcess(string command)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
return new ProcessStartInfo
{
FileName = "cmd.exe",
ArgumentList = { "/c", command },
UseShellExecute = false,
RedirectStandardOutput = true
};
}
else
{
// Linux / macOS
return new ProcessStartInfo
{
FileName = "/bin/sh",
ArgumentList = { "-c", command },
UseShellExecute = false,
RedirectStandardOutput = true
};
}
}
5. Timeouts and Process Tree Cancellation
To prevent hung background processes from tying up server resources, pass a CancellationToken to WaitForExitAsync() and terminate the entire process hierarchy:
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
async Task RunWithTimeoutAsync(string fileName, TimeSpan timeout)
{
using var cts = new CancellationTokenSource(timeout);
using var process = new Process
{
StartInfo = new ProcessStartInfo(fileName)
{
UseShellExecute = false,
CreateNoWindow = true
}
};
process.Start();
try
{
await process.WaitForExitAsync(cts.Token);
Console.WriteLine($"Process finished with exit code {process.ExitCode}");
}
catch (OperationCanceledException)
{
Console.Error.WriteLine("Process timed out. Killing process and descendants...");
// Kill the process and any spawned child processes
process.Kill(entireProcessTree: true);
}
}
6. Summary and Best Practices
- Set
UseShellExecute = false: Required to redirect standard I/O streams (it is the default in .NET Core / .NET 5+, buttruein .NET Framework). - Always Prefer
ArgumentList: Prevents command injection vulnerabilities and cross-platform escaping bugs. - Avoid Deadlocks: When redirecting both
StandardOutputandStandardError, do not read both synchronously one after another. Use asynchronous reads or event handlers. - Clean Up Child Processes: Use
process.Kill(entireProcessTree: true)on cancellations or timeouts so spawned child processes are not orphaned.