How to mimic Stdin input when running an exe from C# using create process?

257 views Asked by At

I have an audio converter .exe that i want to wrap in a C# program, for UI and inputs etc. To use the AudioConverter.exe, it is ran from the console with the suffix " < inputFile > ouputFile". So the full line reads something like

C:\\User\Audioconverter.exe < song.wav > song.ogg

So far i have been able to start the converter succesfully outside of C#, I have managed to have the converter run via create process in C# in a hang state (without input and output files). My code in C# thus far is pretty similar to the answers given on this site:

using System;
using System.Diagnostics;

namespace ConverterWrapper2
{
    class Program
    {
        static void Main()
        {
            LaunchCommandLineApp();
        }
        static void LaunchCommandLineApp()
        {
            // For the example
            const string ex1 = "C:\\Users\\AudioConverter.exe";
            const string ex2 = "C:\\Users\\res\\song.wav";
            const string ex3 = "C:\\Users\\out\\song.ogg";

            // Use ProcessStartInfo class
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.CreateNoWindow = false;
            startInfo.UseShellExecute = false;
            startInfo.FileName = "AudioConverter2.exe";
            startInfo.WindowStyle = ProcessWindowStyle.Normal;
            startInfo.Arguments = ex1 + " < " + ex2 + " > " + ex3; \\Process is ran successfully without the addition of input and output files, but hangs waiting for files.

            try
            {
                using (Process exeProcess = Process.Start(startInfo))
                {
                    exeProcess.WaitForExit();
                }
            }
            catch
            {
                // Log error.
            }
        }
    }
}

So far the converter exe hasnt been able to start up correctly, this leads me to ask the question are inputs for stdin different from arguments?

Regardless i need to mimic this style of input and would appreciate any information. I had assumed that i could just pass the input and output files as arguments but i havent had much luck.

1

There are 1 answers

1
Heinzi On BEST ANSWER
startInfo.Arguments = ex1 + " < " + ex2 + " > " + ex3; \\Process is ran successfully without the addition of input and output files, but hangs waiting for files.

That won't work.

A.exe < B > C is not process A.exe called with arguments < B > C. It's rather a shell instruction to:

  • start A.exe without arguments,
  • read file B and redirect its contents to the new process' stdin and
  • write the new process' stdout to file C.

You have two options to do that in C#:

  1. You can use the help of the shell, i.e., you can start cmd.exe with arguments /c C:\User\Audioconverter.exe < song.wav > song.ogg or

  2. you can re-implement what the shell is doing in C#. A code example for that can be found in this related question: