Skip to content

Instantly share code, notes, and snippets.

@Nonlinearsound
Last active August 8, 2025 22:04
Show Gist options
  • Select an option

  • Save Nonlinearsound/e80c50b5a9264a62dc885e07bbb169d5 to your computer and use it in GitHub Desktop.

Select an option

Save Nonlinearsound/e80c50b5a9264a62dc885e07bbb169d5 to your computer and use it in GitHub Desktop.
Make a dotnet program aware of input redirection via the pipe symbol when used in a CLI environment

Summary

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.

Code

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}");
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment