How can I determine whether Console.Out has been redirected to a file?(如何确定 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.
奖励分.
推荐答案
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 是否已重定向到文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何确定 Console.Out 是否已重定向到文件?


基础教程推荐
- 将 XML 转换为通用列表 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 如何激活MC67中的红灯 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01