开发者

Redirecting std output from Process object to file in .net

Is there a simple way how to launch a process in .NET and redirect its output(s) to a file? I know that in Win API I can pass a file handle to the C开发者_如何学运维reateProcess function. In .NET I can do something like

startInfo.RedirectStandardOutput = true;

and then use BeginOutputReadLine and StandardOutput to get the data and save it to a file. But it seems a bit overhead compared to what OS can handle itself.

Thanks


A bit late, but this pointed me to a better answer: Capturing binary output from Process.StandardOutput

Process cmdProcess = new Process();
ProcessStartInfo cmdStartInfo = new ProcessStartInfo();
cmdStartInfo.FileName = "samtools";

cmdStartInfo.RedirectStandardError = true;
cmdStartInfo.RedirectStandardOutput = true;
cmdStartInfo.RedirectStandardInput = false;
cmdStartInfo.UseShellExecute = false;
cmdStartInfo.CreateNoWindow = true;

cmdStartInfo.Arguments = "view -u " + BamFileName + " " + chromosome + ":" + start + "-" + end;

cmdProcess.EnableRaisingEvents = true;
cmdProcess.StartInfo = cmdStartInfo;
cmdProcess.Start();

using (FileStream str = new FileStream(outputFilePath, FileMode.Create))
{
    cmdProcess.StandardOutput.BaseStream.CopyTo(str);
}

If you want to do this asynchronously, you can use CopyToAsync instead and either await the returned task or add a ContinueWith to finish off. This works great for me.


you can run file as someApp.exe >logfile.txt

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜