Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
117 views
in Technique[技术] by (71.8m points)

c# - How to send series of commands to a command window process?

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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...