开发者

WPF: Read the log from a script executed in the shell?

I use the following code to start an external programm in the command prompt:

private void GenerateTiff(String fileName) {
            bool success = true;
            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += delegate
            {
                try
                {
                    String cmd = @"./lib/gswin32c";
                    String args = "-dNOPAUSE -sDEVICE=pngalpha -r300 -dB开发者_Python百科ATCH -dSAFER -sOutputFile=" + fileName + "-%03d" + FILEEXTENSION + " " + fileName + ".pdf";
                    Process proc = new Process();
                    proc.StartInfo.FileName = cmd;
                    proc.StartInfo.Arguments = args;
                    proc.StartInfo.CreateNoWindow = true;
                    proc.StartInfo.UseShellExecute = false;
                    proc.Start();
                }
                catch (Exception e)
                {
                    success = false;
                }
            };
            worker.RunWorkerCompleted += delegate
            {
                string file = fileName + "-001.jpg";

                if (success) {
                    DisplayImage.Visibility = System.Windows.Visibility.Visible;
                    DisplayImage.Tag = fileName;
                }
            };
            worker.RunWorkerAsync();
        }

Now I'd like to read the log of the command prompt. How can I do that?


Have a look at the Process.StandardOutput property. It provides you with a StreamReader that can be used to read the output of the command.

Be sure to read the documentation, though, since there are some conditions to watch out for, e.g.:

To use StandardOutput, you must set ProcessStartInfo.UseShellExecute to false, and you must set ProcessStartInfo.RedirectStandardOutput to true. Otherwise, reading from the StandardOutput stream throws an exception.

If your external program writes to stderr instead of stdout, use Process.StandardError instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜