Capture output of process synchronously (i.e. “when it happens”)

前端 未结 6 1410
灰色年华
灰色年华 2020-12-18 18:50

I am trying to start a process and capture the output, have come a far way, but am not quite at the solution I\'d want.

Specifically, I am trying to reset the IIS on

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-18 19:38

    I've had that problem and had to solve it when my logs where too long to read in a single readtoend.

    This is what I've done to solve it. It's been doing Ok so far.

                myProcess.StartInfo.FileName = path;
                myProcess.StartInfo.Arguments = args;
                myProcess.StartInfo.UseShellExecute = false;
                myProcess.StartInfo.ErrorDialog = false;
                myProcess.StartInfo.CreateNoWindow = true;
                myProcess.StartInfo.RedirectStandardError = true;
                myProcess.StartInfo.RedirectStandardInput = (stdIn != null);
                myProcess.StartInfo.RedirectStandardOutput = true;
                myProcess.Start();
    
                int index;
                OpenLogFile(myLog);                      //LOGGGGGGGGGGGGG
    
    
                if (myProcess.StartInfo.RedirectStandardInput)
                {
                    StreamWriter sw = myProcess.StandardInput;
                    sw.Write(stdIn + Convert.ToChar(26));
                }
    
                StreamReader sr = myProcess.StandardOutput;
                /*stdOut = new ArrayLi
                */
                while (!sr.EndOfStream)
                {                                           //LOGGGGGGGGGGGGG
                    Log(sr.ReadLine(), true);
                }
    

    Here's OpenLogFile

        private void OpenLogFile(string fileName)
        {
                if (file == StreamWriter.Null)
                {
                    file = new StreamWriter(fileName, true);
                    file.AutoFlush = true;
                }
        }
    

    Of course that Log is a function that does something elsewhere. But the solution to you question lies here:

            while (!sr.EndOfStream)
            {                                           //LOGGGGGGGGGGGGG
                Log(sr.ReadLine(), true);
            }
    

    while stream reader is still reading, you can be writing it down as the log comes out.

提交回复
热议问题