0

使用命令行程序时,通过 ac# 类方法。

您如何确定命令行程序是否成功执行以及它执行的操作是否正常或失败?

另外,如何将屏幕命令行输出输入 c# 类方法?

4

5 回答 5

3

您可以使用 Process 类来执行命令行命令。

以下代码将标准输出捕获到output,并将进程退出代码分配给exitCode

using (Process p = new Process())
{
    p.StartInfo.FileName = exeName;
    p.StartInfo.Arguments = args;
    p.StartInfo.UseShellExecute = false;
    p.StartInfo.RedirectStandardOutput = true;
    p.Start();
    string output = p.StandardOutput.ReadToEnd();
    p.WaitForExit();
    int exitCode = p.ExitCode;
}
于 2011-07-04T16:49:20.547 回答
1

就像是:

Process mycommand = new Process();
mycommand.StartInfo.FileName = "myexe.exe";
mycommand.StartInfo.Arguments = "param1";
mycommand.StartInfo.UseShellExecute = false;
mycommand.StartInfo.RedirectStandardOutput = true;
mycommand.Start();    
Console.WriteLine(mycommand.StandardOutput.ReadToEnd());
mycommand.WaitForExit();

您通常确定 exe 的状态是否退出代码为 0,但这可以说取决于 exe 的编写者

于 2011-07-04T16:46:26.790 回答
0

我假设您正在使用Process该类来调用命令行应用程序。

您可以使用 找到进程的退出代码Process.ExitCode。您可以在启动它之前通过设置重定向它的标准输出ProcessStartInfo.RedirectStandardOutput,然后使用Process.StandardOutputProcess.OutputDataReceived事件。

于 2011-07-04T16:44:33.117 回答
0

看看这个问题在此处输入链接描述

您可能需要的其他信息是process.ExitCode查看它是否成功。当然,控制台应用程序的 Main 方法在不成功时必须返回一个退出代码,很多人不这样做。

于 2011-07-04T16:48:09.423 回答
0

为此,您使用该Process.Start方法。您可以使用传入的参数控制进程的运行方式ProcessStartInfo

var myProcess = Process.Start(new ProcessStartInfo {
  FileName = "process.exe",
  UseShellExecute = false,
  RedirectStandardOutput = true,
  CreateNoWindow = true
});
if (!myProcess.WaitForExit(5000)) { // give it 5 seconds to exit
  myProcess.Kill();
}
if (myProcess.ExitCode != 0) {
  // error!
}
var output = myProcess.StandardOutput.ReadToEnd(); // access output
于 2011-07-04T16:49:37.107 回答