如果我的程序正在打印到控制台,我会根据 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 是否已重定向到文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
读取 XML 时忽略空格Ignore whitespace while reading XML(读取 XML 时忽略空格)
带有检查空元素的 XML 到 LINQXML to LINQ with Checking Null Elements(带有检查空元素的 XML 到 LINQ)
在 C# 中读取带有未闭合标签的 XMLReading XML with unclosed tags in C#(在 C# 中读取带有未闭合标签的 XML)
在 C# 中使用 Html 敏捷性解析表格、单元格Parsing tables, cells with Html agility in C#(在 C# 中使用 Html 敏捷性解析表格、单元格)
使用 LINQ 从 xml 中删除元素delete element from xml using LINQ(使用 LINQ 从 xml 中删除元素)
解析格式错误的 XMLParse malformed XML(解析格式错误的 XML)