Distinguishing Keyboard Input from File Redirection in C# Console Apps
This article demonstrates how to determine if a C# console application's input originates from the keyboard or a redirected file. This capability is vital for creating applications that adapt their behavior based on the input source.
Method Using P/Invoke
The Windows API function FileType()
offers a solution. This functionality is wrapped in the following C# helper class:
<code class="language-csharp">public static class ConsoleEx { private enum FileType { Unknown, Disk, Char, Pipe }; private enum StdHandle { Stdin = -10, Stdout = -11, Stderr = -12 }; [DllImport("kernel32.dll")] private static extern FileType GetFileType(IntPtr hdl); [DllImport("kernel32.dll")] private static extern IntPtr GetStdHandle(StdHandle std); public static bool IsInputRedirected { get { return FileType.Char != GetFileType(GetStdHandle(StdHandle.Stdin)); } } }</code>
Implementation
To check for redirected input, simply use:
<code class="language-csharp">bool isRedirected = ConsoleEx.IsInputRedirected;</code>
Alternative: .NET 4.5 and Later
For .NET Framework 4.5 and later versions, the Console
class provides built-in properties:
Console.IsInputRedirected
Console.IsOutputRedirected
Console.IsErrorRedirected
These properties offer a more straightforward approach to detecting input redirection. Choose the method best suited to your project's .NET framework version.
The above is the detailed content of How Can I Determine if a C# Console Application's Input is from the Keyboard or a File?. For more information, please follow other related articles on the PHP Chinese website!