-1
プロセスの出力とエラーストリームをリダイレクトし、outputdatarecievedとerrordatareceivedハンドラを介して非同期的に結果を取得しています。 正常に動作していますが、出力結果とエラーが空の場合があります。 ここにコードスニペットがあります。ハンドルがまったく呼び出されないか、ストリームに何も書き込まずに処理が終了すると、出力データとエラーデータの両方が空になります。空プロセスの出力とエラーストリームのリダイレクション中の結果
public static string start_proc(string proc_name, string param, int
timeout=8000)
{
string Proc_Data = string.Empty;
StringBuilder outputdata =new StringBuilder("");
StringBuilder errordata = new StringBuilder("");
Process Proc = new Process();
ProcessStartInfo ProcStartInfo = new ProcessStartInfo(proc_name,
param);
ProcStartInfo.UseShellExecute = false;
ProcStartInfo.RedirectStandardOutput = true;
ProcStartInfo.RedirectStandardError = true;
ProcStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
ProcStartInfo.CreateNoWindow = true;
Proc.StartInfo = ProcStartInfo;
Proc.EnableRaisingEvents = true;
Proc.OutputDataReceived += new DataReceivedEventHandler((object
sender, DataReceivedEventArgs args) =>
OutputHandler(outputdata,sender,args));
Proc.ErrorDataReceived += new DataReceivedEventHandler((object
sender, DataReceivedEventArgs args) => OutputHandler(errordata,
sender,args)):
Proc.Start();
Proc.BeginOutputReadLine();
Proc.BeginErrorReadLine(); Proc.WaitForExit(timeout);
Proc_Data = outputdata.Append(errordata).ToString();
Proc.Close();
return Proc_Data;
}
private static void OutputHandler(StringBuilder data, object
sendingProcess,DataReceivedEventArgs outLine)
{
if (!String.IsNullOrEmpty(outLine.Data))
{
data.Append(Environment.NewLine + outLine.Data);
}
}