您能否解释一下为什么 shell 重定向不适用于 System.Diagnostics.Process 类?我正在尝试使用以下代码段将输出流重定向到文件:
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();
类似的代码在 Python 中运行没有问题。 在我的案例中,以编程方式读取输出流似乎不是一个可取的解决方案,因为我的应用程序将启动一堆进程。
最佳答案
您无法进行重定向,因为没有直接涉及的 shell。您可以运行 cmd.exe session ,但正确的方法是使用 RedirectStandardOutput/Error 属性。有很多进程时没有问题。这是我为此使用的类(class)。
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# - c#中重定向stdout的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3051704/