2011-07-04 31 views
0

当使用命令行程序时,通过c#类方法。命令行程序/ app + C#类方法

如何确定命令行程序是否已成功执行并且其执行的操作是否正常或失败?

另外你如何获得屏幕命令行输出到C#类的方法?

+0

的[捕获.NET中的控制台输出(C#)](可能重复http://stackoverflow.com/questions/186822/capturing-the -console -input-in-net-c) –

回答

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; 
} 
+0

我也将编写控制台应用程序,如何在控制台应用程序中设置exitCode?只需在完成执行后返回代码吧? – 001

+0

只需从Main()返回错误级别代码。请参阅http://msdn.microsoft.com/en-us/library/0fwzzxz2.aspx。 –

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

0

的作家看看这个问题enter link description here

您可能需要的附加信息是process.ExitCode以查看它是否成功。当然,控制台应用程序的主要方法必须在不成功时返回退出代码,而许多代码则不会。

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