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 是否已重定向到文件?


- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- 使用 rss + c# 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01