我有一个程序,我有一个.exe文件。 .exe的工作是扫描目录中是否存在损坏的文件。如果通过命令提示符以下列格式访问,我将获得扫描结果
“exe”的位置“”要扫描的文件或文件夹“
我得到的结果是扫描继续进行。喜欢
D:\A scanned
D:\B scanned
D:\C scanned
D:\D scanned
现在我的问题是如何使用c#逐行获得结果。
我正在使用以下代码集,我只得到最终结果。我需要逐行输出
代码如下:
string tempGETCMD = null;
Process CMDprocess = new Process();
System.Diagnostics.ProcessStartInfo StartInfo = new System.Diagnostics.ProcessStartInfo();
StartInfo.FileName = "cmd"; //starts cmd window
StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
StartInfo.CreateNoWindow = true;
StartInfo.RedirectStandardInput = true;
StartInfo.RedirectStandardOutput = true;
StartInfo.UseShellExecute = false; //required to redirect
CMDprocess.StartInfo = StartInfo;
CMDprocess.Start();
System.IO.StreamReader SR = CMDprocess.StandardOutput;
System.IO.StreamWriter SW = CMDprocess.StandardInput;
SW.WriteLine("@echo on");
SW.WriteLine(@"E:\Scanner\Scanner.exe -r E:\Files to be scanned\"); //the command you wish to run.....
SW.WriteLine("exit"); //exits command prompt window
tempGETCMD = SR.ReadToEnd(); //returns results of the command window
SW.Close();
SR.Close();
return tempGETCMD;
任何有关这方面的帮助都会受到赞赏
谢谢,
答案 0 :(得分:1)
我认为您必须使用专用线程来读取StandardOutput
流中的每一个新行,如下所示:
//This will append each new line to your textBox1 (multiline)
private void AppendLine(string line)
{
if (textBox1.InvokeRequired){
if(textBox1.IsHandleCreated) textBox1.Invoke(new Action<string>(AppendLine), line);
}
else if(!textBox1.IsDisposed) textBox1.AppendText(line + "\r\n");
}
//place this code in your form constructor
Shown += (s, e) => {
new Thread((() =>
{
while (true){
string line = CMDProcess.StandardOutput.ReadLine();
AppendLine(line);
//System.Threading.Thread.Sleep(100); <--- try this to see it in action
}
})).Start();
};
//Now every time your CMD outputs something, the lines will be printed (in your textBox1) like as you see in the CMD console window.