0

我有一个程序,其中有一个 .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;

对此的任何帮助将不胜感激

谢谢,

4

1 回答 1

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.       
于 2013-08-24T14:50:59.047 回答