This short example shows, how to detect the usage of a pipe in a CLI environment to redirect the input buffer of your program to the output of another process.
This code is the minimal API version of a dotnet program. It has been tested on SDK 9.0 on MacOS. By using Console.IsInputRedirected the code detects, if the input buffer has been redirected to the output of the piping process and uses that instead. If the user provides a filename instead, that file is read and printed to the output. If no argument is given, the program waits for the users input and prints that instead.
using System;
using System.IO;
// If input is redirected (piped), read from stdin
if (Console.IsInputRedirected)
{
using (Stream stream = Console.OpenStandardInput())
using (StreamReader reader = new StreamReader(stream))
{
string? line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
// If no arguments provided and no input redirection, read from stdin interactively
else if (args.Length == 0)
{
Console.WriteLine("No input redirection detected and no files specified.");
Console.WriteLine("Enter text (Ctrl+D to end on Unix, Ctrl+Z on Windows):");
string? line;
while ((line = Console.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
// If arguments provided, treat them as file paths
else
{
foreach (string filePath in args)
{
try
{
if (File.Exists(filePath))
{
string[] lines = File.ReadAllLines(filePath);
foreach (string line in lines)
{
Console.WriteLine(line);
}
}
else
{
Console.Error.WriteLine($"cat: {filePath}: No such file or directory");
}
}
catch (Exception ex)
{
Console.Error.WriteLine($"cat: {filePath}: {ex.Message}");
}
}
}