【发布时间】:2014-03-03 15:54:02
【问题描述】:
我找到了很多关于如何执行 cmd.exe 和执行命令,甚至执行 nslookup 和交互的编码示例,但我遇到的问题是一个特定的 dos 程序,当它启动时,它不会停止“输出”。这是一些代码,我将发表评论以及我从 C# 得到的错误
这是我如何以更高级的方式设置它,以便我可以接收来自程序的事件输出
public void StartApplication(string appNameAndPath)
{
StreamReader outputStream;
Process p = new Process();
p.StartInfo.FileName = appNameAndPath;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = false;//for now just so I can see it
p.Start();
//here is my advanced example
if(advanced == true)
{
outputStream = p.StandardOutput;
DoReadOutPut();
}
else
{//here is a simple example
while (p.StandardOutput.ReadLine() != null) //this hangs here until the application exists
{
txt += (p.StandardOutput.ReadLine());
}
}
}
void DoReadOutput()
{
outputStream.BaseStream.BeginRead( readOutputBuffer, 0, readOutputBuffer.Length, new AsyncCallback( OnReadOutputCompleted ), null );
//this does sometimes fire but only with 0 bytes, on other dos programs it would say Memory read not allowed
}
void OnReadOutputCompleted( IAsyncResult result )
{
int cbRead = outputStream.BaseStream.EndRead( result );
ProcessOutput( readOutputBuffer, cbRead );
DoReadOutput();
}
private void ProcessOutput(byte[] buffer, int cbRead)
{
string text = p.StartInfo.StandardOutputEncoding.GetString(buffer, 0, 10000); //this is where it hangs until the program exits or is not writing anymore
this.Invoke((Action)delegate
{
SetTextBoxValue(text);//im doing this because im on another thread otherwise textBox1.Text - text"
});
}
我不想使用 API 和 GetText 并为 ReadLastLine 创建一个引擎,有人可以帮我吗?我想你会想要一个示例 exe,创建一个 while(true){Console.WriteLine("bla");} 足以作为示例 exe 而不是我遇到问题的 exe 的 C# 应用程序。 exe接管dos窗口并具有“老派界面”
【问题讨论】:
-
您是否尝试过使用
Process.OutputDataReceived事件? msdn.microsoft.com/en-us/library/… -
我会快速尝试一下
-
Diamondo25 我试过了,程序继续运行,当我在调试时点击暂停时,它转到 sortProcess.WaitForExit(); 之后的行。并且从未进入 SortOutputHandler 事件
-
你确定程序输出到stdout,而不是stderr?
-
不知道出处,幸好他们有一个允许输出的参数
标签: c# multithreading cmd