Skip to content

Instantly share code, notes, and snippets.

@ridercz
Created January 20, 2025 22:29
Show Gist options
  • Save ridercz/7517737d217cd160460c0d891db3f349 to your computer and use it in GitHub Desktop.
Save ridercz/7517737d217cd160460c0d891db3f349 to your computer and use it in GitHub Desktop.
Running external process with stdin/out/err redirection
// Video: https://youtu.be/cdTu27j6dn8
using System.Diagnostics;
using System.Text;
// Verify there are exactly 2 arguments and get source and destination folders
if (args.Length != 2) {
Console.WriteLine("Usage: mirror <source folder> <destination folder>");
return;
}
var sourceFolder = args[0];
var destinationFolder = args[1];
// Create process start info to run ROBOCOPY
var psi = new ProcessStartInfo {
FileName = "robocopy.exe", // Name of the executable
UseShellExecute = false, // Cannot use shell execute when redirecting IO
CreateNoWindow = true, // Don't create visible window
RedirectStandardOutput = true, // Redirect stdout to the process object
RedirectStandardError = true, // Redirect stderr to the process object
RedirectStandardInput = true, // Redirect stdin to the process object
StandardOutputEncoding = Encoding.UTF8, // Encoding for stdout
StandardErrorEncoding = Encoding.UTF8, // Encoding for stderr
StandardInputEncoding = Encoding.UTF8, // Encoding for stdin
};
// Add command line arguments - it's better than concatenating strings to Arguments property
psi.ArgumentList.Add(sourceFolder); // Source folder
psi.ArgumentList.Add(destinationFolder); // Destination folder
psi.ArgumentList.Add("/MIR"); // Mirror the source folder
psi.ArgumentList.Add("/NP"); // Don't show progress percentage
// Run ROBOCOPY
using var process = Process.Start(psi);
if (process == null) {
Console.WriteLine("Error: Failed to start ROBOCOPY");
return;
}
#region Option 1: Read all stdout data at once
Console.Write("Running ROBOCOPY... ");
var output = process.StandardOutput.ReadToEnd();
Console.WriteLine("OK");
Console.WriteLine(output);
#endregion
#region Option 2: Read stdout data line by line
//while (!process.StandardOutput.EndOfStream) {
// var line = process.StandardOutput.ReadLine();
// Console.WriteLine(line);
//}
#endregion
#region Option 3: Read stdout data asynchronously as received
//process.OutputDataReceived += (sender, e) => Console.WriteLine(e.Data);
//process.BeginOutputReadLine();
//process.WaitForExit();
#endregion
// Check exit code
Console.WriteLine($"Exit code: {process.ExitCode}");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment