0

I want to run an exe utility which produces some binary output (which is an image) based on given parameters. I need to get the binary output of the utility as a stream (MemoryStream) and the Errors (if any). It is also required to have a Timeout such that if app hangs or it takes a long time to respond, break its execution and return what ever result it output until that time.

One way is to use cmd like as:

cmd /C ... >out.jpg 2>err.txt

But this requires a temp file which is not acceptable, i want to capture output data directly as it should be called many times and output size is large.

The basic code to run the process is as following:

using (var p = new Process())
{
    //p.StartInfo = new ProcessStartInfo("cmd", "/C " + command + " > x.jpg 2> err.txt");
    p.StartInfo = new ProcessStartInfo()
    {
        FileName = @"x.exe", //dcraw
        Arguments = @"-c -e x.jpg", 
        UseShellExecute = false, //it is usefull for non-exe like as for a Word file.
        RedirectStandardOutput = true,
        RedirectStandardError = true,
        CreateNoWindow = true,
        WindowStyle = ProcessWindowStyle.Hidden
    };
    int timeout = 5000; //msec

    p.Start();

    //MemoryStream outputStream = ...
    //p.OutputDataReceived += ... //can't use this as it returns text not binary data

    //string errorText = ...

    p.WaitForExit();

    //return new pResult(Image.FromStream(outputStream), errorText, isTimedout, ...);

}

How to get outputStream and errorText with specified timeout?

Note: I know there are several questions about process.start and output redirecting. Most of them are about capturing text output not binary data (like this or that). And this binary question does not answer my question completely as stated here (capturing both output and errors at the same time may cause dead-end locks, no timeout specified).

S.Serpooshan
  • 7,608
  • 4
  • 33
  • 61
  • I/O redirection is a pretty leaky abstraction that should have stayed in Unix. It cannot be binary, only readable text encoded in a code page that uses 8-bit code units can redirect correctly. Having both programs agree about the encoding to use is in itself a gritty problem. Generate a file instead, pass the file path as an argument. Using a pipe or socket is not impossible, hard to test. – Hans Passant Jan 03 '18 at 10:41
  • @HansPassant but i think it is possible to capture output as binary if i don't care about capturing the errors too. eg: using `Process.StandardOutput.BaseStream`. so the encoding should not be an issue – S.Serpooshan Jan 03 '18 at 10:48

0 Answers0