Home > Backend Development > C++ > How Can I Determine if a C# Console Application's Input is from the Keyboard or a File?

How Can I Determine if a C# Console Application's Input is from the Keyboard or a File?

DDD
Release: 2025-01-12 17:12:43
Original
786 people have browsed it

How Can I Determine if a C# Console Application's Input is from the Keyboard or a File?

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>
Copy after login

Implementation

To check for redirected input, simply use:

<code class="language-csharp">bool isRedirected = ConsoleEx.IsInputRedirected;</code>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template