About redirected stdout in System.Diagnostics.Process

Posted by sforester on Stack Overflow See other posts from Stack Overflow or by sforester
Published on 2010-05-29T05:23:51Z Indexed on 2010/05/29 5:32 UTC
Read the original article Hit count: 286

Filed under:
|
|

I've been recently working on a program that convert flac files to mp3 in C# using flac.exe and lame.exe, here are the code that do the job:

ProcessStartInfo piFlac = new ProcessStartInfo( "flac.exe" );
piFlac.CreateNoWindow = true;
piFlac.UseShellExecute = false;
piFlac.RedirectStandardOutput = true;
piFlac.Arguments = string.Format( flacParam, SourceFile );

ProcessStartInfo piLame = new ProcessStartInfo( "lame.exe" );
piLame.CreateNoWindow = true;
piLame.UseShellExecute = false;
piLame.RedirectStandardInput = true;
piLame.RedirectStandardOutput = true;
piLame.Arguments = string.Format( lameParam, QualitySetting, ExtractTag( SourceFile ) );

Process flacp = null, lamep = null;
byte[] buffer = BufferPool.RequestBuffer();


flacp = Process.Start( piFlac );
lamep = new Process();
lamep.StartInfo = piLame;
lamep.OutputDataReceived += new DataReceivedEventHandler( this.ReadStdout );
lamep.Start();
lamep.BeginOutputReadLine();

int count = flacp.StandardOutput.BaseStream.Read( buffer, 0, buffer.Length );

while ( count != 0 )
{
    lamep.StandardInput.BaseStream.Write( buffer, 0, count );

    count = flacp.StandardOutput.BaseStream.Read( buffer, 0, buffer.Length );
}

Here I set the command line parameters to tell lame.exe to write its output to stdout, and make use of the Process.OutPutDataRecerved event to gather the output data, which is mostly binary data, but the DataReceivedEventArgs.Data is of type "string" and I have to convert it to byte[] before put it to cache, I think this is ugly and I tried this approach but the result is incorrect.

Is there any way that I can read the raw redirected stdout stream, either synchronously or asynchronously, bypassing the OutputDataReceived event?

PS: the reason why I don't use lame to write to disk directly is that I'm trying to convert several files in parallel, and direct writing to disk will cause severe fragmentation.

Thanks a lot!

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET