标准输出重定向在C#中的问题 [英] the problem of redirecting stdout in c#
问题描述
能否请您解释一下为什么shell重定向不符合的System.Diagnostics.Process类的工作?我试图重定向输出流用下面的代码片段到文件:
Could you please explain why the shell redirection doesn't work with System.Diagnostics.Process class? I am trying to redirect the output streams to file with the following snippet:
Process p = new Process();
p.StartInfo = new ProcessStartInfo();
p.StartInfo.FileName = "java.exe";
p.StartInfo.Arguments = @"> c:\Temp\test.log 2>&1";
p.StartInfo.UseShellExecute = true;
p.Start();
类似的code没有问题的作品与Python。 读输出流编程似乎并不preferable解决方案,在我的情况,因为将有一堆我的应用程序启动的进程。
The similar code works without problems with Python. Reading the output streams programmatically doesn't seem a preferable solution in my case because there will be a bunch of processes launched by my application.
推荐答案
您不能执行重定向,因为没有外壳直接参与。你可以运行cmd.exe的会话,但正确的方法是使用RedirectStandardOutput /错误性质。具有许多工艺时是没有问题的。这是一类我用这个。
You cannot do the redirection because there is no shell directly involved. You could run a cmd.exe session, but the proper way to do it is using the RedirectStandardOutput/Error properties. There is no problem when having many processes. This is a class I use for this.
class HandleExecutable {
private DataReceivedEventHandler outputHandler;
public DataReceivedEventHandler OutputHandler
{
set { outputHandler = value; }
}
private DataReceivedEventHandler errorHandler;
public DataReceivedEventHandler ErrorHandler
{
set { errorHandler = value; }
}
public void callExecutable(string executable, string args)
{
string commandLine = executable;
string args = args;
ProcessStartInfo psi = new ProcessStartInfo(commandLine);
psi.UseShellExecute = false;
psi.LoadUserProfile = false;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.WindowStyle = ProcessWindowStyle.Minimized;
psi.CreateNoWindow = true;
psi.Arguments = args;
p = new Process();
p.StartInfo = psi;
try
{
p.Start();
p.BeginOutputReadLine();
p.BeginErrorReadLine();
if (outputHandler != null) p.OutputDataReceived += outputHandler;
if (errorHandler != null) p.ErrorDataReceived += errorHandler;
p.WaitForExit();
p.Close();
p.Dispose();
}
catch (Exception ex)
{
log.Error(ex.Message);
}
}
}
//On another class
void p_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
//HANDLE STDERR
if (e.Data != null && !e.Data.Equals(""))
{
if (!e.Data.Contains("Something")) {
}
}
}
void p_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
//HANDLE STDOUT
if (e.Data != null && !e.Data.Equals(""))
{
}
}
HandleExecutable he = new HandleExecutable();
he.OutputHandler = p_OutputDataReceived;
he.ErrorHandler = p_ErrorDataReceived;
he.callExecutable(@"C:\java.exe","-cp foo ClassName");
这篇关于标准输出重定向在C#中的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!