process.standardoutput.ReadToEnd() always empty?

前端 未结 4 810
你的背包
你的背包 2020-12-10 04:14

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

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-10 04:41

    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;
        }
    

提交回复
热议问题