在 VB.net 中写入控制台和标准输出
我有一个正在写入控制台的 winform 应用程序,它似乎运行良好。我正在使用这段代码:
AttachConsole(-1)
Console.Out.WriteLine("Hellow world")
FreeConsole()
问题是: 如果我从命令行运行应用程序的 exe 文件,并尝试将输出重定向到文件中。这不起作用。 例如:
C:\ > myapp.exe > c:\output.txt
我仍然将输出输出到控制台屏幕(c:\output.txt 文件已创建但为空),但我希望将其保存到 c:\output.txt 出了什么问题?怎么做呢?
非常感谢!
I have a winform app that is writing to console and it seems to work well. I'm using this code:
AttachConsole(-1)
Console.Out.WriteLine("Hellow world")
FreeConsole()
The question is:
If I run the app's exe file from command line, and try to redirect the output into a file. It doesn't work.
For example:
C:\ > myapp.exe > c:\output.txt
I still get the output to console screen (c:\output.txt file is created but empty), but I want it to to be saved into c:\output.txt
What's going wrong ? How to do that?
Many thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您首先检查输出是否被重定向,那么您可以鱼与熊掌兼得。这是一个包含 P/Invoke voodoo 的小帮助器类:
用法:
You can have your cake and eat it too if you first check if output was redirected. Here's a little helper class that contains the P/Invoke voodoo:
Usage:
您正在附加到父进程以提供输出,在您的情况下可能是 cmd.exe。父进程的 stdout 流尚未重定向,因此继续在屏幕上显示输出。
我不知道有直接的方法。如果您不调用
AttachConsole
,您会发现重定向按预期工作,但当然您会失去拥有控制台窗口的选项。然而,有一个我认为合理的解决方法。如果您希望输出转到控制台窗口,那么您可以为应用程序提供一个指示此要求的命令行开关,例如
当
/console
参数存在时,您可以调用AttachConsole
并且输出将被写入控制台。当此开关不存在时,您不会调用AttachConsole
并且您将能够将输出重定向到文件。You are attaching to the parent process to provide output, which in your case is probably cmd.exe. The parent process' stdout stream has not been redirected and therefore continues to display the output on the screen.
I am not aware of a direct approach. If you do not call
AttachConsole
you will find that the redirect works as expected, but of course then you loose the option to have a console window. However, there is a work around that I think is reasonable.If you want the output to go to a console window then you provide your application with a commandline switch that indicates this requirement, something like
When the
/console
argument is present you callAttachConsole
and the output will be written to the console. When this switch is not present you do not make the call toAttachConsole
and you will be able to redirect the output to a file.