问题描述
如果我的程序正在打印到控制台,我会根据 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.
奖励分.
推荐答案
p/invoke 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
.
这篇关于如何确定 Console.Out 是否已重定向到文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!