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 是否已重定向到文件?
基础教程推荐
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
