Get Live output from Process

后端 未结 6 1264
灰色年华
灰色年华 2020-11-30 04:44

I\'ve a problem in my project. I would like to launch a process, 7z.exe (console version). I\'ve tried three different things:

  • Process.StandardOutput.ReadToEnd
6条回答
  •  半阙折子戏
    2020-11-30 05:19

    Take a look at this page, it looks this is the solution for you: http://msdn.microsoft.com/en-us/library/system.diagnostics.process.beginoutputreadline.aspx and http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx

    [Edit] This is a working example:

            Process p = new Process();
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.FileName = @"C:\Program Files (x86)\gnuwin32\bin\ls.exe";
            p.StartInfo.Arguments = "-R C:\\";
    
            p.OutputDataReceived += new DataReceivedEventHandler((s, e) => 
            { 
                Console.WriteLine(e.Data); 
            });
            p.ErrorDataReceived += new DataReceivedEventHandler((s, e) =>
            {
                Console.WriteLine(e.Data);
            });
    
            p.Start();
            p.BeginOutputReadLine();
            p.BeginErrorReadLine();
    

    Btw, ls -R C:\ lists all files from the root of C: recursively. These are a lot of files, and I'm sure it isn't done when the first results show up in the screen. There is a possibility 7zip holds the output before showing it. I'm not sure what params you give to the proces.

提交回复
热议问题