我正在尝试从 C# 运行命令行实用程序 PCLI.exe,但没有成功。我正在构建一个 ProcessStartInfo 对象并设置了 process.StartInfo.RedirectStandardOutput = true,但是当我尝试读取 process.StandardOutput 时出现以下错误:
Message=StandardOut 尚未重定向或进程尚未启动。
我什至尝试将命令的输出通过管道传输到 output.txt,但在创建文件时它是空的。
该过程已完成但并未真正执行预期的文件,因此我正在 try catch StandardOutput 以查看发生了什么。仅出于后台目的,我正在尝试运行 PVCS get 命令以从 PVCS 中获取文件。
这是我的代码片段:
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new
System.Diagnostics.ProcessStartInfo();
process.StartInfo.RedirectStandardOutput = true;
startInfo.UseShellExecute = false;
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
startInfo.WorkingDirectory = "c:\\gitmover";
startInfo.FileName = "C:\\Program Files (x86)\\Serena\\vm\\win32\\bin\\pcli.exe";
Console.WriteLine("Password:?");
string password = Console.ReadLine();
for (int i = 0; i < revisionsArray.Count(); i++)
{
string fileName = "/" + file.Key.Substring(file.Key.IndexOf("Customers")).Replace('\\','/');
startInfo.Arguments = "get -r" + revisionsArray[i] + " -id\"beng:" + password + "\" -prM:\\Engineering\\SOUP -o -ac:/gitmover -bp'/Customers' -z " + fileName + "> output.txt";
process.StartInfo = startInfo;
process.Start();
string strOutput = process.StandardOutput.ReadToEnd();
//Wait for process to finish
process.WaitForExit();
}
最佳答案
尝试将您的进程包装在 using
中,并使用 StreamReader
读取标准输出。
var start = new ProcessStartInfo
{
FileName = _pathToPythonExecutable,
Arguments = string.Format(" {0}", _pathToPythonCalibratorScript),
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardInput = true,
RedirectStandardError = true,
WorkingDirectory = _currentWorkingDirectory
};
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
result = reader.ReadToEnd();
}
}
关于c# - 无法从 C# 运行命令并捕获 StandardOutput,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28748453/