0

I am trying to implement piping behavior in C#.NET using Process and ProcessStartInfo classes. My intention is to feed the output of previous command to next command so that that command will process the input and return result. have a look into following code -

private static string Out(string cmd, string args, string inputFromPrevious)
{
    string RetVal = string.Empty;
    try
    {
        ProcessStartInfo psi = String.IsNullOrEmpty(args) ? new ProcessStartInfo(cmd) : new ProcessStartInfo(cmd, args);
        psi.RedirectStandardOutput = true;
        psi.RedirectStandardError = true;
        psi.WindowStyle = ProcessWindowStyle.Hidden;
        psi.UseShellExecute = false;
        psi.RedirectStandardInput = string.IsNullOrEmpty(inputFromPrevious) ? false : true;

        Process proc = new System.Diagnostics.Process();
        proc.StartInfo = psi;

        if (proc.Start())
        {
            if (!string.IsNullOrEmpty(inputFromPrevious))
            {
                proc.StandardInput.AutoFlush = true;
                proc.StandardInput.WriteLine(inputFromPrevious); proc.StandardInput.WriteLine();
                proc.StandardInput.Close();
            }

            using (var output = proc.StandardOutput)
            {
                Console.WriteLine("3. WAITING WAITING....."); < ---Code halts here.
                RetVal = output.ReadToEnd();
            }
        }
        proc.WaitForExit();
        proc.Close();
    }
    catch (Exception Ex)
    {

    }
    return RetVal; < ---This is "inputFromPrevious" to next call to same function
}

I am calling above code in loop for different commands and arguments. Is there any mistake in my code? I had looked similar as shown below but nothing worked for me as of now. Any help will be appreciated.

Piping in a file on the command-line using System.Diagnostics.Process

Why is Process.StandardInput.WriteLine not supplying input to my process?

Repeatably Feeding Input to a Process' Standard Input

Community
  • 1
  • 1
Omkar
  • 2,129
  • 8
  • 33
  • 59
  • So, what is the problem? Is the method throwing exception, behaving in an unexpected way, or what? – Mateusz Krzaczek Dec 21 '16 at 11:58
  • No exception is thrown. Basically I guess, since I am calling multiple commands in loop and creating different instances of Process class which is happening asynchronously. So next command is started before output of previous command is ready. – Omkar Dec 22 '16 at 06:45
  • Are you calling this outside of the class?, because you probably need to ensure that the the modifier is public instead of private. – Netferret Dec 22 '16 at 10:46

0 Answers0