【问题标题】:Display Batch output in TextBox在 TextBox 中显示批量输出
【发布时间】:2013-10-25 15:11:07
【问题描述】:

我尝试使用以下代码从 c# 运行批处理文件,我想在 WPF 文本框中显示结果。你能指导我怎么做吗?

using System;

namespace Learn
{
    class cmdShell
    {
        [STAThread]  // Lets main know that multiple threads are involved.
        static void Main(string[] args)
        {
            System.Diagnostics.Process proc; // Declare New Process
            proc = System.Diagnostics.Process.Start("C:\\listfiles.bat"); // run test.bat from command line.
            proc.WaitForExit(); // Waits for the process to end.
        }
    }
}

此批处理文件用于列出文件夹中的文件。批处理执行后,结果应显示在文本框中。如果批处理文件有多个命令,则每个命令的结果都应显示在文本框中

【问题讨论】:

  • 结果来自不同的文件因此不同的进程,您可以使用 Pipe(或 WCF)访问您的应用程序,您将无法找出这些结果

标签: c# wpf batch-file process command-line-arguments


【解决方案1】:

你需要重定向标准输出流:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Process proc = new Process();
            proc.StartInfo.FileName = "test.bat";
            proc.StartInfo.UseShellExecute = false;
            proc.StartInfo.RedirectStandardOutput = true;
            proc.Start();
            string output = proc.StandardOutput.ReadToEnd();
            Console.WriteLine(output); // or do something else with the output
            proc.WaitForExit();
            Console.ReadKey();
        }
    }
}

【讨论】:

  • 是的,这工作正常。但是一旦执行完成就会显示输出,是否需要为此添加任何内容?
  • StandardOutput 类的StandardOutput 属性是StreamReader 实例。您无需等待执行结束。例如:如果您在循环中使用proc.StandardOutput.ReadLine(),您可以等待下一行被写入并立即将其推送到您的文本框。有关详细信息,请参阅文档。
【解决方案2】:

我已经解决了进程挂起和立即获得输出的问题,如下所示

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Process proc = new Process();
            proc.StartInfo.FileName = "test.bat";
            proc.StartInfo.UseShellExecute = false;
           proc.StartInfo.RedirectStandardOutput = true;
            proc.OutputDataReceived += proc_OutputDataReceived;
            proc.Start();
            proc.BeginOutputReadLine();
        }
    }


        void proc_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            this.Dispatcher.Invoke((Action)(() =>
                        {
                            txtprogress.Text = txtprogress.Text + "\n" + e.Data;
                            txtprogress.ScrollToEnd();
                        }));
        }
}

【讨论】:

    猜你喜欢
    • 2016-07-14
    • 2012-03-09
    • 2017-11-05
    • 1970-01-01
    • 1970-01-01
    • 2020-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多