0

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 -dBATCH -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?

  • one:http://stackoverflow.com/questions/164736/redirect-standard-output-efficiently-in-net – Felice Pollano Mar 03 '11 at 16:41
  • another:http://stackoverflow.com/questions/3051704/the-problem-of-redirecting-stdout-in-c – Felice Pollano Mar 03 '11 at 16:42
  • 1
    Your function is called Generate*Tiff*, you add -001.*jpg* to the file name and the parameter that you pass to GhostScript indicates that you are in fact creating a *png* file. Are you sure you got your file formats sorted out? – Heinzi Mar 03 '11 at 16:44
  • Yes ;) It's because first I created png. Then i created tiffs and then I tried to use jpeg. But you're right... its a reason to refactor it. –  Mar 03 '11 at 16:49

1 Answers1

2

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.

Heinzi
  • 167,459
  • 57
  • 363
  • 519