如何解决从流程重定向时,为什么会丢失输出?
| 我正在使用Process类调用控制台应用程序。我将输出重定向到日志文件,但是当我不重定向输出时,控制台窗口中的消息多于我时不在日志文件中的消息。有什么想法吗?ProcessStartInfo psi = new ProcessStartInfo();
string filename = @\"ProgrammingMaster_LocalPowertrain.exe\";
psi.FileName = filename;
string arguments = String.Format(\"{0} {1} false\",InstanceId.ToString(),ManifestFolderPath);
psi.Arguments = arguments;
LogMessage(msgType.Warning,filename + \" - \" + arguments);
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
psi.RedirectStandardError = true;
psi.RedirectStandardOutput = true;
FBlockProcess = new Process();
FBlockProcess.StartInfo = psi;
FBlockProcess.OutputDataReceived += new DataReceivedEventHandler(FBlockProcess_OutputDataReceived);
FBlockProcess.ErrorDataReceived += new DataReceivedEventHandler(FBlockProcess_ErrorDataReceived);
FBlockProcess.Start();
FBlockProcess.BeginOutputReadLine();
FBlockProcess.BeginErrorReadLine();
在我的OutputDataReceived处理程序中,我只是将字符串添加到ConcurrentQueue
编辑:
我应该补充一点,我想实时或接近捕获输出。该过程可能要花费30多分钟才能运行,我不想等那么久才能看到正在发生的事情。
更新:
输出前四行后,就永远不会调用OutputDataReceived eventHandler,即使我知道当我不进行重定向时,还会有10或15行输出到控制台。有什么想法可能导致这种情况吗?
解决方法
试试这个例子:
public static void Main()
{
Process p = new Process();
p.StartInfo.FileName = \"cmd.exe\";
p.StartInfo.Arguments = \"/c dir *.cs\";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
string output = p.StandardOutput.ReadToEnd();
Console.WriteLine(\"Output:\");
Console.WriteLine(output);
}
更新
我认为您可以在这里尝试一些有用的方法:
http://msdn.microsoft.com/zh-CN/library/system.diagnostics.process.errordatareceived.aspx
更新
我发现此链接,听起来“解决方案1”是正确的方法:
http://www.codeproject.com/Answers/152467/Problem-executing-a-command-line-command-from-Csha.aspx?cmt=49313#answer1
, 当尝试与需要身份验证的应用程序进行交互时,我遇到了类似的问题。当遇到时髦的字符(unicode字符?)时,Peek()将返回-1,并且ReadLine()也不可靠,并且由于似乎进程的标准流未关闭,最终将锁定我的应用程序。
使用Read()方法是我可以确保获得所有行和字符的唯一方法。另外,使用Process的ErrorDataReceived或OutputDataReceived事件处理程序还证明是不可关联的(缺少行)。以下是我如何解决问题并为收到的所有行和字符提供保险的方式:
process.Start();
var stdOutput = process.StandardOutput;
StringBuilder fullMessage = new StringBuilder();
while (true)
{
var character = (char)stdOutput.Read();
fullMessage.Append(character);
//Print Out All Characters
Console.Write(character);
if (fullMessage.ToString().EndsWith(\"Enter Password: \"))
{
//Submit Password To Application
using(StreamWriter writer = process.StandardInput){
writer.Write(\"somepassword\");
writer.Flush();
}
break;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。