【问题标题】:WPF: Read the log from a script executed in the shell?WPF:从 shell 中执行的脚本中读取日志?
【发布时间】:2011-03-04 00:38:57
【问题描述】:

我使用以下代码在命令提示符下启动外部程序:

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

现在我想阅读命令提示符的日志。我该怎么做?

【问题讨论】:

  • 您的函数名为 GenerateTiff,您将 -001.*jpg* 添加到文件名中,您传递给 GhostScript 的参数表明您实际上是在创建一个png 文件。你确定你的文件格式已经整理好了吗?
  • Yes ;) 这是因为我首先创建了 png。然后我创建了 tiffs,然后我尝试使用 jpeg。但你是对的......这是重构它的理由。

标签: c# .net wpf


【解决方案1】:

查看Process.StandardOutput 属性。它为您提供了一个 StreamReader,可用于读取命令的输出。

不过,请务必阅读文档,因为有些情况需要注意,例如:

要使用 StandardOutput,您必须将 ProcessStartInfo.UseShellExecute 设置为 false,并且必须将 ProcessStartInfo.RedirectStandardOutput 设置为 true。否则,从 StandardOutput 流中读取会引发异常。

如果您的外部程序写入 stderr 而不是 stdout,请改用 Process.StandardError

【讨论】:

    猜你喜欢
    • 2019-07-26
    • 1970-01-01
    • 2014-12-07
    • 2018-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-21
    相关资源
    最近更新 更多