我正在编写一个C#的winform应用程序,它启动第二个进程来执行shell命令,例如“dir”和“ping”。我重定向第二个进程的输出,这样我的应用程序就可以接收命令结果。它基本上运行得很好。
唯一的问题是我的winform应用程序会整体接收命令行输出,而不是逐行接收。例如,它必须等待外部“ping”命令完成(需要很长时间或更长时间),然后一次性接收整个输出内容(多行)。
我想要的是应用程序实时按行接收cmdline输出,而不是按块接收。这可行吗?
我正在使用以下代码读取输出: while ((result = proc.StandardOutput.ReadLine()) != null)
但它并没有按照我的预期工作。 谢谢。
编辑:这是我正在使用的代码:
唯一的问题是我的winform应用程序会整体接收命令行输出,而不是逐行接收。例如,它必须等待外部“ping”命令完成(需要很长时间或更长时间),然后一次性接收整个输出内容(多行)。
我想要的是应用程序实时按行接收cmdline输出,而不是按块接收。这可行吗?
我正在使用以下代码读取输出: while ((result = proc.StandardOutput.ReadLine()) != null)
但它并没有按照我的预期工作。 谢谢。
编辑:这是我正在使用的代码:
System.Diagnostics.ProcessStartInfo procStartInfo = new
System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
procStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
// The following commands are needed to redirect the standard output.
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = true;
// Now we create a process, assign its ProcessStartInfo and start it
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
// Get the output into a string
string result;
try {
while ((result = proc.StandardOutput.ReadLine()) != null)
{
AppendRtfText(result+"\n", Brushes.Black);
}
} // here I expect it to update the text box line by line in real time
// but it does not.