【发布时间】:2015-11-03 19:34:14
【问题描述】:
我有一个小应用程序,它有一个信息文本框,假设向它输出执行的命令。
目前我已对其进行了设置,以便 Console.Write[WriteLine] 正确附加到文本框。该代码如下:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
// bind the console output to the new text box
var writer = new TextBoxStreamWriter(x_OutputTextBox);
Console.SetOut(writer);
Console.SetError(writer);
}
}
internal class TextBoxStreamWriter : TextWriter
{
static TextBox _text = null;
public TextBoxStreamWriter(TextBox outputBox)
{
_text = outputBox;
}
public override void Write(string value)
{
base.Write(value);
_text.Dispatcher.Invoke(() => _text.AppendText(string.Format("{0} - {1}", DateTime.Now, value)));
}
public override void WriteLine(string value)
{
base.WriteLine(value);
_text.Dispatcher.Invoke(() => _text.AppendText(string.Format("{0} - {1}", DateTime.Now, value + Environment.NewLine)));
}
public override Encoding Encoding
{
get { return Encoding.UTF8; }
}
}
这一切都很好而且花花公子,但是当我尝试从批处理文件输出回显结果时,我遇到了问题。我查看了有关该主题的许多问题/答案,例如:View Output in a Batch (.bat) file from C# code 但这些选项对我不起作用。 当WriteLine 或Write 函数的覆盖被调用时,它只是挂起并且不写任何东西。我该如何解决?
我的Process 实现如下:
Process process = new Process();
process.OutputDataReceived += ReadOutput;
process.ErrorDataReceived += ReadErrorOutput;
process.EnableRaisingEvents = true;
//process.StartInfo = new ProcessStartInfo(@"cmd.exe", @"/c " + Path.Combine(Environment.CurrentDirectory, "BatchFile", "test.bat"))
process.StartInfo = new ProcessStartInfo(Path.Combine(Environment.CurrentDirectory, "BatchFile", "test2.bat"))
{
UseShellExecute = false,
Verb = "runas",
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true,
//WorkingDirectory = Path.Combine(Environment.CurrentDirectory, "BatchFile", "Information.bat"),
WorkingDirectory = Path.Combine(Environment.CurrentDirectory, "BatchFile") + @"\",
};
process.Start();
process.BeginErrorReadLine();
process.BeginOutputReadLine();
process.WaitForExit();
输出重定向:
private void ReadOutput(object sender, DataReceivedEventArgs e)
{
if (e.Data == null)
return;
Console.Write(e.Data);
}
private void ReadErrorOutput(object sender, DataReceivedEventArgs e)
{
if (e.Data == null)
return;
Console.Write(e.Data);
}
目前批处理文件超级简单:
echo off
echo Finding Information
echo .......................
echo foo bar is cool
echo this day kinda sucks
echo .......................
echo All Processes Complete!
【问题讨论】:
标签: c# wpf batch-file