我怎样才能确定是否Console.Out已被重定向到一个文件?已被、重定向、文件、Console

2023-09-02 01:48:54 作者:闹够了就滚

如果我的程序打印到控制台,我以某种方式进行自动换行根据Console.WindowWidth通过插入新行 - 这完美的作品

If my program is printing to the console, I perform word-wrapping in a certain way according to Console.WindowWidth by inserting newlines - and this works perfectly.

但是,如果该程序的输出重定向到文件或其他程序,我想它跳过自动换行。我如何可以检测到这种情况?

However if the output of the program is redirected to a file or another program I would like it to skip the word-wrapping. How can I detect when this is the case?

Console.WindowWidth返回在两种情况下相同的号码。

Console.WindowWidth returns the same number in both cases.

奖金分,如果该解决方案可以从重定向Console.Error区分重定向Console.Out。

Bonus points if the solution can distinguish redirected Console.Out from redirected Console.Error.

推荐答案

P /调用 GetFileType(GetStdHandle(STD_OUTPUT_HANDLE)),或致电像一个无害的控制台功能 GetConsoleScreenBufferInfo 来检查无效句柄错误。如果您想了解标准错误,使用 STD_ERROR_HANDLE 。我相信,你甚至可以比较 GetStdHandle(STD_OUTPUT_HANDLE)返回的句柄 GetStdHandle(STD_ERROR_HANDLE)来检测的东西,如 2 - ;&安培; 1

p/invoke GetFileType(GetStdHandle(STD_OUTPUT_HANDLE)), or call an innocuous console function like GetConsoleScreenBufferInfo to check for invalid handle error. If you want to know about standard error, use STD_ERROR_HANDLE. I believe you can even compare handles returned by GetStdHandle(STD_OUTPUT_HANDLE) and GetStdHandle(STD_ERROR_HANDLE) to detect stuff like 2>&1.