在C#DLL文件中将其作为进程运行时,如何获取控制台应用程序输出? [英] How can I obtain console application output when running it as a process in a C# DLL file?

查看:376
本文介绍了在C#DLL文件中将其作为进程运行时,如何获取控制台应用程序输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究DLL中的方法。在我的方法中,我一直在写事件日志,以使我能够确定事情是否按预期进行。我在该方法中执行的任务之一是创建一个进程并运行一个命令行应用程序,我希望能够捕获通常写入控制台的结果并将其写入事件日志。

I am working on method in a DLL. In my method I have been writing to the event log to allow me to determine whether things are working as I expect. One of the tasks I do in the method is create a process and run a command line application and I want to be able to capture the output of this that is normally written to the console and write it to the eventlog.

代码:

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());

我有一个控制台测试应用程序,该应用程序调用了我的方法,当我这样做时,我可以看到该过程已开始并正确运行,但是当我实际上尝试使用DLL而不是使用测试应用程序时,我最终看到的只是一个条目:

I have a console test application that calls my method and when I do this I am able to see that the process was started and ran correctly, however when I actually try to make use of the DLL, not using the test application, all I end up seeing is an entry:

IPS:而且没有任何输出。但是,我可以看到它正在运行,因为我可以看到许多输出文件正在更新。

IPS: And none of the output. I can tell it is running, however, as I can see a number of output files being updated.

为什么我没有任何输出以及如何纠正此问题?

Why am I not getting any output and how I can rectify this?

推荐答案

在您的库中,应该直接使用
System.Diagnostics.Trace 。通过使用Trace,您可以使用 TraceListener

In your library, instead of writing directly to the location of choice you should be using System.Diagnostics.Trace. By using Trace you can have your outside console application or whatever it be subscribe to the Trace event using a TraceListener.

通过使用Trace和TraceListeners,您可以使应用程序适应所需的任何记录情况,而不必每次都修改您的库您想更改日志记录系统。

By using Trace and TraceListeners, you can make you application adaptable to whatever logging situation you require without having to modify your library every time you want to change the logging system.

下面是另一个有关跟踪日志记录的Stack Overflow线程的链接,其中包含一些很好的示例和信息。

Below is a link to another Stack Overflow thread about trace logging with some good examples and information.

如何在C#中添加(简单)跟踪?

这篇关于在C#DLL文件中将其作为进程运行时,如何获取控制台应用程序输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆