Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
549 views
in Technique[技术] by (71.8m points)

c# - process.standardoutput.ReadToEnd() always empty?

I'm starting a console application, but when I redirect the standard output I always get nothing!

When I don't redirect it, and set CreateNoWindow to false, I see everything correctly in the console, but when I redirect it, StandardOutput.ReadToEnd() always returns an empty string.

        Process cproc = new Process();
        cproc.StartInfo.CreateNoWindow = true;
        cproc.StartInfo.FileName = Dest;
        cproc.StartInfo.RedirectStandardOutput = true;
        cproc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        cproc.StartInfo.UseShellExecute = false;
        cproc.EnableRaisingEvents = true;
        cproc.Start();
        cproc.Exited += new EventHandler(cproc_Exited);
        while(!stop)
        {
           result += cproc.StandardOutput.ReadToEnd();
        }

The EventHandler cproc_exited just sets stop to true. Can someone explain why result is always string.Empty?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Best way for this is to redirect the output and wait for the events:

    // not sure if all this flags are needed
    process.StartInfo.CreateNoWindow = true;
    process.StartInfo.ErrorDialog = false;
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardError = true;
    process.StartInfo.RedirectStandardInput = true;
    process.StartInfo.RedirectStandardOutput = true;
    process.EnableRaisingEvents = true;
    process.OutputDataReceived += process_OutputDataReceived;
    process.ErrorDataReceived += process_ErrorDataReceived;
    process.Exited += process_Exited;
    process.Start();

    void process_Exited(object sender, System.EventArgs e)
    {
        // do something when process terminates;
    }

    void process_OutputDataReceived(object sender, DataReceivedEventArgs e)
    {
        // a line is writen to the out stream. you can use it like:
        string s = e.Data;
    }

    void process_ErrorDataReceived(object sender, DataReceivedEventArgs e)
    {
        // a line is writen to the out stream. you can use it like:
        string s = e.Data;
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...