0

我尝试使用以下代码从 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.
        }
    }
}

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

4

2 回答 2

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.Start();
            string output = proc.StandardOutput.ReadToEnd();
            Console.WriteLine(output); // or do something else with the output
            proc.WaitForExit();
            Console.ReadKey();
        }
    }
}
于 2013-10-24T11:07:27.753 回答
0

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

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();
                        }));
        }
}
于 2013-10-25T07:11:07.970 回答