如何从Process.Start获取日志

时间:2010-07-21 05:48:33

标签: c# asp.net precompiler

我将在我的自定义c#表单中预编译一个asp.net应用程序。如何检索流程日志并检查流程是否成功?

这是我的代码

string msPath = "c:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\\";
string msCompiler = "aspnet_compiler.exe";
string fullCompilerPath = Path.Combine(msPath, msCompiler);
msPath.ThrowIfDirectoryMissing();
fullCompilerPath.ThrowIfFileIsMissing();

ProcessStartInfo process = new ProcessStartInfo 
{ 
    CreateNoWindow = false,
    UseShellExecute = false,
    WorkingDirectory = msPath,
    FileName = msCompiler,
    Arguments = "-p {0} -v / {1}"
        .StrFormat(
            CurrentSetting.CodeSource,
            CurrentSetting.CompileTarget)
};

Process.Start(process);

谢谢!

2 个答案:

答案 0 :(得分:5)

ProcessStartInfo.RedirectStandardOutput设置为true - 这会将所有输出重定向到Process.StandardOutput,这是您可以读取的流以查找所有输出消息:

ProcessStartInfo process = new ProcessStartInfo 
{ 
   CreateNoWindow = false,
   UseShellExecute = false,
   WorkingDirectory = msPath,
   RedirectStandardOutput = true,
   FileName = msCompiler,
   Arguments = "-p {0} -v / {1}"
            .StrFormat(
              CurrentSetting.CodeSource, 
              CurrentSetting.CompileTarget)
};

Process p = Process.Start(process);
string output = p.StandardOutput.ReadToEnd();

您也可以使用{@ 1}}事件与@Bharath K在答案中描述的方式类似。

OutputDataReceived有类似的属性/事件 - 您还需要将StandardError设置为RedirectStandardError

答案 1 :(得分:2)

在ErrorDataReceived事件的源应用程序寄存器中:

StringBuilder errorBuilder = new StringBuilder( );
reportProcess.ErrorDataReceived += delegate( object sender, DataReceivedEventArgs e )
{
    errorBuilder.Append( e.Data );
};
//call this before process start
reportProcess.StartInfo.RedirectStandardError = true;
//call this after process start
reportProcess.BeginErrorReadLine( );

目标应用程序中抛出的任何错误都可以将数据写入此中。像这样:

Console.Error.WriteLine( errorMessage ) ;