有如下代码(主要部分)Process p=new Process();
p.StartInfo.FileName=@"c:\windows\system32\cmd.exe";
p.StartInfo.RedirectStandardError=true;
p.StartInfo.RedirectStandardInput=true;
p.StartInfo.RedirectStandardOutput=true;
p.StartInfo.UseShellExecute=false;
p.Start();p.StandardInput.WriteLine("dir c:\\");
string str=p.StandardOutput.ReadToEnd();//问题所在Console.WriteLine(str);问题在于执行到p.StandardOutput.ReadToEnd();时候就一直阻塞,调试发现的确读完了命令行输出数据,但可能是缺少流结束符所以无法结束Read;如果使用StandardOutput.ReadLine()无法知道读到哪行才读完本次的输出数据。问有什么方法可以既读完dir c:\\的输出,又能使ReadToEnd();及时返回?

解决方案 »

  1.   

      if (p.HasExited)
                {                
                    //从输出流获取执行结果 
                    strRst = p.StandardOutput.ReadToEnd();
                }
      

  2.   

    static void Main(string[] args)
            {
                Process ps = new Process();
                ps.StartInfo.FileName = "cmd.exe";
                ps.StartInfo.RedirectStandardOutput = true;
                ps.StartInfo.RedirectStandardInput = true;
                ps.StartInfo.CreateNoWindow = true;
                ps.StartInfo.UseShellExecute = false;
                ps.StartInfo.StandardOutputEncoding = System.Text.Encoding.Default;
                ps.StartInfo.RedirectStandardError = false;
                ps.OutputDataReceived += new DataReceivedEventHandler(ps_OutputDataReceived);            ps.Start();
                ps.BeginOutputReadLine();
                ps.StandardInput.WriteLine(@"dir c:\");
                ps.StandardInput.Close();
                ps.WaitForExit();
                ps.Close();
            }
            static void ps_OutputDataReceived(object sender, DataReceivedEventArgs e)
            {
                if (e.Data == null)
                {
                    return;
                }
                Console.Write(e.Data+"\n");
            }
      

  3.   

    correctusing System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    using System.Globalization;
    using System.Text.RegularExpressions;
    using System.Diagnostics;
    using System.Threading;namespace CSharp
    {    class Program
        {
            static void Main(string[] args)
            {            Process p = new Process();
                p.StartInfo.FileName = "cmd.exe";
                p.StartInfo.RedirectStandardError = true;
                p.StartInfo.RedirectStandardInput = true;
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.UseShellExecute = false;
                p.Start();            p.StandardInput.WriteLine("dir c:\\");
                p.StandardInput.WriteLine("exit");
                string str = p.StandardOutput.ReadToEnd();
                Console.WriteLine(str);
                Console.ReadLine();
            }    }
    }
      

  4.   

    StandardOutput.ReadLine()为空的时候不就是输入完成的时候了吗?