Output Chaining using C# Process and ProcessStartInfo i.e. Piping implementation in C#

489 views Asked by At

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

0

There are 0 answers