How can I get console application output when starting it as a process in c # dll

I am working on a method in a DLL. In my method, I wrote to the event log so that I can determine if things work as I expect. One of the tasks that I perform in the method is to create a process and run a command line application, and I want to be able to write the output of this, which is usually written to the console and writes it to the event log.

the code:

Process getNextIons = new Process(); getNextIons.StartInfo.FileName = @"""C:\Program Files\OpenMS- 1.6\PrecursorIonSelector.exe"""; getNextIons.StartInfo.Arguments = @"-ini ""C:\Program Files\OpenMS-1.6\precursorionselector.ini"""; getNextIons.StartInfo.UseShellExecute = false; getNextIons.StartInfo.RedirectStandardOutput = true; getNextIons.Start(); getNextIons.WaitForExit(); System.Diagnostics.EventLog.WriteEntry("FMANWiff", "IPS: " + getNextIons.StandardOutput.ReadToEnd()); 

I have a console test application that calls my method, and when I do this, I can see that the process was started and started correctly, however, when I actually try to use the DLL without using the test application, all I I see this entry:

IPS: and none of the output. I can say that it works, since I can see how the number of output files is updated.

Does anyone know why I am not getting any result and how can I fix it?

+1
source share
2 answers

In your library, instead of writing directly to your chosen location, you should use System.Diagnostics.Trace . Using Trace, you can use an external console application or something else that subscribes to the Trace event using the TraceListener .

Using Trace and TraceListeners, you can make the application adaptable to any logging situation that you need, without having to change your library every time you want to change the logging system.

Below is a link to another StackOverflow trace protocol thread, with some good examples and information.

How to add (simple) trace in C #?

+1
source

According to the Process.StandardOutput documentation, your code has a potential deadlock.

When the caller reads from a redirected stream of a child process, it depends on the child. The caller waits for a read operation until the child writes to the stream or closes the stream. When a child process writes enough data to populate a redirected stream, it depends on the parent. The child process waits for the next write operation until the parent reads the full stream or closes the stream. A deadlock condition occurs when the calling and child processes are waiting for each other to complete the operation, and cannot continue.

To avoid possible deadlocks, you must switch the last two lines of your code. You should also consider redirecting a StandardError.

+1
source

All Articles