我怎样才能确定是否Console.Out已被重定向到一个文件? [英] How can I determine whether Console.Out has been redirected to a file?

查看:308
本文介绍了我怎样才能确定是否Console.Out已被重定向到一个文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的程序打印到控制台,我以某种方式进行自动换行根据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.

这篇关于我怎样才能确定是否Console.Out已被重定向到一个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆