【发布时间】:2011-03-02 16:16:27
【问题描述】:
public void ExecuteProcessChain(string[] asProcesses, string sInRedirect, string sOutRedirect)
{
Process p1 = new Process();
p1.StartInfo.UseShellExecute = false;
p1.StartInfo.RedirectStandardOutput = true;
p1.StartInfo.FileName = asProcesses[0];
p1.Start();
StreamReader sr = p1.StandardOutput;
string s, xxx = "";
while ((s = sr.ReadLine()) != null)
Console.WriteLine("sdfdsfs");
//xxx += s+"\n";
p1.StartInfo.RedirectStandardInput = true;
p1.StartInfo.RedirectStandardOutput = false;
p1.StartInfo.FileName = asProcesses[1];
p1.Start();
StreamWriter sw = p1.StandardInput;
sw.Write(xxx);
sw.Close();
sr.Close();
}
我正在尝试执行“calc|calc”,但是当我这样做时,它会卡在while ((s = sr.ReadLine()) != null) 行,并且只有在我关闭计算器后代码才会继续。我需要两个计算器一起工作。你知道怎么做吗?
【问题讨论】:
-
你为什么用
while ((s = sr.ReadLine()) != null)这个语句? -
因为我需要读取数据,例如: ls|sort ,我需要读取 ls 行并对其进行排序。
-
这是否偶然地与 Roy Gavrielov 的作业相同?:how can I check if the process got output? 即使变量名相同,我对他问题的回答也应该对您有用。
-
顺便说一句,您不必关闭读写器,因为它们不会绑定任何非托管资源。根据经验,只有在创建流、读取器或写入器时才应关闭它。如果它是 IDisposable(适用于所有 Streams 和大多数 Readers 和 Writers),则应尽可能使用 using statement。这与关闭 Stream 的效果相同,但更易于阅读并防止一些常见错误。
-
我注意到的其他一些小事情:
string s, xxx = "";仅将xxx设置为"",s 未初始化。函数的参数按照Systems Hungarian命名。这可能是你的任务的一部分,但它是generally seen as bad practice, especially in C#。这是一篇关于这个主题的有趣文章:Making Wrong Code Look Wrong
标签: c# streamreader chain