Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send series of commands to a command window process?

Tags:

c#

process

cmd

We have a few commands(batch files/executables) on our network path which we have to call to initialize our 'development environment' for that command window. It sets some environmental variables, adds stuff to the Path etc. (Then only whatever working commands we type will be recognized & I don't know what goes inside those initializing commands)

Now my problem is, I want to call a series of those 'working commands' using a C# program, and certainly, they will work only if the initial setup is done. How can I do that? Currently, I'm creating a batch file by scratch from the program like this for example:

file.Writeline("InitializationStep1.bat")
file.Writeline("InitializeStep2.exe")
file.Writeline("InitializeStep3.exe")

Then the actual commands

file.Writeline("Dowork -arguments -flags -blah -blah")
file.Writeline("DoMoreWork -arguments -flags -blah -blah")

Then finally close the file writer, and run this batch file.

Now if I directly execute this using Process.<strike>Run</strike>Start("cmd.exe","Dowork -arguments"); it won't run.

How can I achieve this in a cleaner way, so that I have to run the initialization commands only once? (I could run cmd.exe each time with all three initializers, but they take a lot of time so I want to do it only once)

like image 394
Piyush Soni Avatar asked Jan 25 '11 00:01

Piyush Soni


1 Answers

As @Hakeem has pointed out, System.Diagnostic.Process does not have a static Run method. I think you are referring to the method Start.
Once you have completed building the batch file, then simply execute it using the following code,

Process p = new Process();
p.StartInfo.FileName = batchFilePath;
p.StartInfo.Arguments = @"-a arg1 -b arg2";
p.Start();

Note that the @ symbol is required to be prefixed to the argument string so that escape sequence characters like \ are treated as literals.

Alternative code

Process.Start(batchFilePath, @"-a arg1 -b arg2");

or

ProcessStartInfo processStartInfo = new ProcessStartInfo();
processStartInfo.FileName = batchFilePath;
processStartInfo.Arguments = @"-a arg1 -b arg2";
Process.Start(processStartInfo);


More information

  • Process.Start method

Example of multi command batch file

dir /O
pause
dir
pause

Save this file as .bat and then execute using the Start method. In this case you can specify the argument with the command in the batch file itself (in the above example, the /O option is specified for the dir command.
I suppose you already have done the batch file creation part, now just append the arguments to the commands in the batch file.

Redirecting Input to a process
Since you want to send multiple commands to the same cmd process, you can redirect the standard input of the process to the take the input from your program rather than the keyboard.

Code is inspired from a similar question at: Execute multiple command lines with the same process using C#

private string ProcessRunner()
{
    ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd.exe");
    processStartInfo.RedirectStandardInput = true;
    processStartInfo.RedirectStandardOutput = true;
    processStartInfo.UseShellExecute = false;

    Process process = Process.Start(processStartInfo);

    if (process != null)
    {
        process.StandardInput.WriteLine("dir");
        process.StandardInput.WriteLine("mkdir testDir");
        process.StandardInput.WriteLine("echo hello");
        //process.StandardInput.WriteLine("yourCommand.exe arg1 arg2");

        process.StandardInput.Close(); // line added to stop process from hanging on ReadToEnd()

        string outputString = process.StandardOutput.ReadToEnd();
        return outputString;
    }

    return string.Empty;
}

The method returns the output of the command execution. In a similar fashion, you could also redirect and read the StandardOuput stream of the process.

like image 93
Devendra D. Chavan Avatar answered Oct 20 '22 00:10

Devendra D. Chavan