我尝试使用以下代码从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.
}
}
}
此批处理文件用于列出文件夹中的文件。批处理执行后,结果应显示在文本框中。如果批处理文件包含多个命令,则每个命令的结果应显示在文本框中。
答案 0 :(得分: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();
}
}
}
答案 1 :(得分: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();
}));
}
}