c#中重定向过程标准输入、标准输出和标准错误
本文关键字:标准输出 标准 错误 标准输入 重定向 过程 | 更新日期: 2023-09-27 17:49:18
我想用批处理文件编译一个java程序。如果程序不需要任何输入,但在需要输入时创建死锁条件,则代码可以工作下面是代码:
public void compilefile(ref System.Windows.Controls.RichTextBox rtb,ref TabItem tabitem)
{
var range = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd);
FileInfo filetocompile = new FileInfo(Path.GetTempPath() + tabitem.Header.ToString());
using (FileStream fs = filetocompile.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
{
range.Save(fs, System.Windows.DataFormats.Text);
fs.Close();
}
try{
pf = new ProcessStartInfo(@"E:'com.bat");
pf.FileName = @"E:'com.bat";
pf.Arguments = string.Format("{0} {1} {2} {3} {4}", "'"C:''Program Files (x86)''Java''jdk1.7.0_13''bin'''"", "javac", tabitem.Header.ToString(), "java", tabitem.Header.ToString().Substring(0, tabitem.Header.ToString().LastIndexOf('.')));
pf.CreateNoWindow = true;
pf.ErrorDialog = false;
pf.UseShellExecute = false;
pf.RedirectStandardInput = true;
pf.RedirectStandardOutput = true;
pf.RedirectStandardError = true;
pf.WorkingDirectory = Path.GetTempPath();
p = new Process();
p.StartInfo = pf;
p.Start();
input = p.StandardInput;
string inputstring = "";
input.AutoFlush = true;
do
{
if (p.StandardError.ReadToEnd() != "")
{
consoleTextBlock.IsDocumentEnabled = false;
consoleTextBlock.AppendText(p.StandardOutput.ReadToEnd());
consoleTextBlock.AppendText(p.StandardError.ReadToEnd());
}
else
{
consoleTextBlock.AppendText(p.StandardOutput.ReadToEnd());
consoleTextBlock.AppendText(p.StandardError.ReadToEnd());
}
consoleTextInput.Focus();
consoleTextBlock.ScrollToEnd();
consoleTextBlock.IsReadOnly = true;
System.Windows.MessageBox.Show(p.ExitCode.ToString());
} while (p.HasExited != true);
}
catch (Exception ex)
{
System.Windows.MessageBox.Show(ex.ToString());
}
}
我应该用什么来重定向输入?
先输入,然后在事件结束后读取两个输出流,如下所示:
//..
string[] inputLines = {"your", "input", "goes", "here"}
//..
//..
p.Start();
using (StreamWriter sw = p.StandardInput)
{
if (sw.BaseStream.CanWrite)
foreach(string line in inputLines) sw.WriteLine(line);
}
string output = "+";
string outputErr = "-";
output = p.StandardOutput.ReadToEnd();
outputErr = p.StandardError.ReadToEnd();
p.WaitForExit();