"句柄无效"运行通过Java .NET控制台时,句柄、台时、QUOT、NET

2023-09-03 17:01:32 作者:11.当歌纵马

我试图运行通过Java点网控制台应用程序:

I'm trying to run dot net console application via Java:

process = Runtime.getRuntime().exec(commandLine);

我得到以下的输出:

I get the following output:

Detecting
The handle is invalid.

直接通过控制台(视窗)运行

当它没有问题:

when running it directly via the console (windows) there is no problem:

Detecting
100%
Done.
100%

我正在以这种形式更多的应用程序,但也没问题。

I'm running more applications in this form but have no problem .

得到这个堆栈跟踪:

Detecting at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
 at System.Console.GetBufferInfo(Boolean throwOnNoConsole, Boolean& succeeded)
 at System.Console.get_CursorTop()
 at AutomaticImageOrientation.HelperClasses.General.WriteProgressToConsole(Int32 lastIndex, Int32 totalImages)
 at AutomaticImageOrientation.MainManager.DetectImage(String[] files, String outputPath, String& globalErrorMessage, Dictionary`2& foundRotations)

现在的问题是,当.NET应用程序试图写入控制台如何解决?

The problem is when the .net app trying to write to the console What is the solution?

发现导致问题的行:

Console.CursorLeft = 0;

你知道为什么吗?

Do you know why?

推荐答案

控制台应用程序试图以设置控制台光标位置。这是不可能的,因为在没有事实控制台。所有操作而不会导致一个简单的读或写有可能导致错误的时候没有控制台(因为他们大多数都需要一个控制台输出缓冲器工作)。

The console application is trying to set the cursor position for a console. This isn't possible, since there is in fact no console. All operations which don't result in a simple read or write are likely to cause errors when there is no console (since most of them require a console output buffer to work).

这是一个坏主意,做的东西,如设置光标位置或清除屏幕在控制台应用程序要自动化。一个基本的解决办法是,只是把有问题的语句在try-catch和丢弃异常。从上System.Console 的 MSDN页面:

It is a bad idea to do stuff like setting the cursor position or clearing the screen in console applications you wish to automate. A basic workaround is to just put the offending statement in a try-catch, and discard the exception. From the MSDN page on System.Console:

您不应使用Console类   在无人值守显示输出   应用中,如服务器   应用程序。同样,调用   方法如Write和WriteLine   在Windows中没有任何影响   应用程序。

You should not use the Console class to display output in unattended applications, such as server applications. Similarly, calls to methods such as Write and WriteLine have no effect in Windows applications.

控制台类成员   通常当底层流   定向到一个控制台可能抛出   但如果该流重定向,   例如,到一个文件。因此,   编写应用程序,以赶上   如果您重定向System.IO.IOException   一个标准的数据流。

Console class members that work normally when the underlying stream is directed to a console might throw an exception if the stream is redirected, for example, to a file. Consequently, program your application to catch System.IO.IOException if you redirect a standard stream.