MS' own console.cs has the following function, used by the IsInput/Output/ErrorRedirected APIs.
private static bool IsHandleRedirected(IntPtr ioHandle) {
// Need this to use GetFileType:
SafeFileHandle safeIOHandle = new SafeFileHandle(ioHandle, false);
// If handle is not to a character device, we must be redirected:
int fileType = Win32Native.GetFileType(safeIOHandle);
if ((fileType & Win32Native.FILE_TYPE_CHAR) != Win32Native.FILE_TYPE_CHAR) // <--- ??
return true;
// We are on a char device.
// If GetConsoleMode succeeds, we are NOT redirected.
int mode;
bool success = Win32Native.GetConsoleMode(ioHandle, out mode);
return !success;
}
I don't understand the logic on the line marked (by me) with // <--- ??. It would have made sense that if (fileType != Win32Native.FILE_TYPE_CHAR) return true;, but I don't follow why it's masked with & Win32Native.FILE_TYPE_CHAR before comparing.
To make it more confusing, the constant FILE_TYPE_CHAR is the single bit 0x0002 which is also shared by FILE_TYPE_PIPE = 0x0003, so the if statement in question will not return true; if the file handle refers to a pipe (maybe relying on GetConsoleMode to fail afterwards??).
Any insight into why that code was written the way it is would be much appreciated. Thanks.