我想从 C# 运行一个 shell 命令并在我的程序中使用返回的信息。所以我已经知道要从终端运行某些东西,我需要做这样的事情:
string strCmdText;
strCmdText= "p4.exe jobs -e";
System.Diagnostics.Process.Start("CMD.exe",strCmdText);
所以现在执行命令,并从这个命令返回一些信息......我的问题是如何在我的程序中使用这些信息,可能与命令行参数有关,但不确定。
我真的需要使用 C#。
您可以使用ProcessStartInfo重定向输出。MSDN和SO上有示例。
例如
Process proc = new Process {
StartInfo = new ProcessStartInfo {
FileName = "program.exe",
Arguments = "command line arguments to your executable",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
然后启动该过程并从中读取:
proc.Start();
while (!proc.StandardOutput.EndOfStream) {
string line = proc.StandardOutput.ReadLine();
// do something with line
}
根据您要完成的工作,您还可以取得更多成就。我编写了将数据异步传递到命令行并从中读取的应用程序。这样的例子不容易发布在论坛上。