如何在C#中捕获EXE文件返回的响应

3

我希望能够将参数传递给另一个由C#开发的exe文件。 我知道如何从我的应用程序向exe文件传递参数。这样我就可以传递参数到exe文件。

Process p= new Process();
p.StartInfo.FileName = "demo.exe";
p.StartInfo.Arguments = "param1 param2";
p.Start();
p.WaitForExit();

现在demo.exe文件将会执行某些任务并返回一些数据。我想在我的端口捕获这些数据。请指导我如何更改我的代码以捕获demo.exe文件返回的响应。请提供修改后的代码。谢谢。
可能下面的解决方案可以解决我的问题。我会测试它。 当您创建Process对象时,请适当设置StartInfo:
var proc = new Process {
    StartInfo = new ProcessStartInfo {
        FileName = "program.exe",
        Arguments = "command line arguments to your executable",
        UseShellExecute = false,
        RedirectStandardOutput = true,
        CreateNoWindow = true
    }
};

then start the process and read from it:

proc.Start();
while (!proc.StandardOutput.EndOfStream) {
    string line = proc.StandardOutput.ReadLine();
    // do something with line
}

1
可能是 https://dev59.com/dG855IYBdhLWcg3whExL 的重复问题。 - Jan Köhler
使用 Process.ExitCode: https://msdn.microsoft.com/zh-cn/library/system.diagnostics.process.exitcode(v=vs.110).aspx - Matjaž
4个回答

2

一种可能的解决方案是使用RedirectStandardOutput,并将结果存储在文件中:

using(Process proc = new Process())
{
    proc.StartInfo.UseShellExecute = false;
    proc.StartInfo.FileName = <your exe>;
    proc.StartInfo.Arguments = <your parameters>;
    proc.StartInfo.RedirectStandardOutput = true;
    proc.OutputDataReceived += LogOutputHandler;
    proc.Start();
    proc.BeginOutputReadLine();
    proc.WaitForExit();
}

private static void LogOutputHandler(object proc, DataReceivedEventArgs outLine)
{
    <write your result to a file here>
}

如何从被我的应用程序调用的exe文件返回值。假设我要调用demo.exe文件,那么我需要编写什么或如何从演示应用程序中返回值,以便我的主要应用程序可以读取该值。请用代码指导我如何返回数据。谢谢。 - Mou

1
简单的解决方法是使用传统的进程退出代码。
一旦进程终止,您可以使用 p.ExitCode 在代码中捕获结果。
此外,demo.exe 需要在退出之前设置 Environment.ExitCode
通常,0 表示成功。

假设demo.exe将返回一个字符串值,我想从我的应用程序中捕获它。请指导我需要编写什么代码? - Mou
许多不同的解决方案可以使用... 简单:您可以将结果输出到文件中,并在其他项目中读取它。 较不容易:您可以像@Beno所提到的那样使用WCF进行跨进程通信。 - Pascal

1
如果进程只是整数,则可以检查其ExitCode。否则,您可以使用WCF管道在进程之间进行通信。

0

main函数的返回值为'void',因此您无法返回任何项。您可以使用标准输出流来传递信息。一种简单的方法是将XML流返回给调用程序,这很容易解析。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接