The Mask
The Mask

Reputation: 17427

Process not working

I have tried calling a Process(console application) using the following code:

       ProcessStartInfo pi = new ProcessStartInfo();
        pi.UseShellExecute = false;
        pi.RedirectStandardOutput = true;
        pi.CreateNoWindow = true;
        pi.FileName = @"C:\fakepath\go.exe";
        pi.Arguments = "FOO BAA";
        Process p = Process.Start(pi);
        StreamReader streamReader = p.StandardOutput;
        char[] buf = new char[256];
        string line = string.Empty;
        int count;
        while ((count = streamReader.Read(buf, 0, 256)) > 0)
        {
            line += new String(buf, 0, count);
        }

It works for only some cases. The file that does not work has a size of 1.30 mb, I don't know if that is the reason for it not working correctly. line returns an empty string. I hope this is clear. Can someone point out my error? Thanks in advance.

Upvotes: 0

Views: 141

Answers (1)

Brandon Langley
Brandon Langley

Reputation: 551

A couple thoughts:

  1. The various Read* methods of streamreader require you to ensure that your app has completed before they run, otherwise you may get no output depending on timing issues. You may want to look at the Process.WaitForExit() function if you want to use this route.

    Also, unless you have a specific reason for allocating buffers (pain in the butt IMO) I would just use readline() in a loop, or since the process has exited, ReadToEnd() to get the whole output. Neither requires you to have to do arrays of char, which opens you up to math errors with buffer sizes.

  2. If you want to go asynchronous and dump output as you run, you will want to use the BeginOutputReadLine() function (see MSDN)

  3. Don't forget that errors are handled differently, so if for any reason your app is writing to STDERR, you will want to use the appropriate error output functions to read that output as well.

Upvotes: 2

Related Questions