Nech
Nech

Reputation: 379

How to run multiple cmd commands from c# console app

I'm looking to automate nupkg creation in a c# app. I'm aiming to include nuget.exe in my project and use System.Diagnostics to launch cmd.exe as a process and then pass the required commands, which would be 'cd project\path\here', 'nuget spec something.dll' and 'nuget pack something.nuspec'.

The code I have so far is:

        Process p = new Process();
        ProcessStartInfo info = new ProcessStartInfo(@"C:\Windows\System32\cmd.exe", @"mkdir testdir");

        p.StartInfo = info;
        p.Start();

        Console.ReadLine();

However, it doesn't even create the testdir, and I've got no idea how to chain those commands. There is a method called WaitForInputIdle on my p Process, but it raises events and I've got no idea how to handle those to be honest.

A perfect solution would also let me read output and input. I've tried using StreamWriter p.StandardInput, but then there's the problem of checking whether a command is finnished and what was the result.

Any help would be much appreciated.

Edit: Success! I've managed to create a directory :) Here's my code now:

    Process p = new Process();
    ProcessStartInfo info = new ProcessStartInfo(@"C:\Windows\System32\cmd.exe");
    info.RedirectStandardInput = true;
    info.UseShellExecute = false;

        p.StartInfo = info;
        p.Start();

        using (StreamWriter sw = p.StandardInput)
        {
            sw.WriteLine("mkdir lulz");
        }

Still no idea how to await for input and follow up with more commands, though.

Upvotes: 1

Views: 2214

Answers (1)

Ghulam Mohayudin
Ghulam Mohayudin

Reputation: 1113

You can do this by three ways

1- The easiest option is to combine the two commands with the '&' symbol.

 var processInfo = new ProcessStartInfo("cmd.exe", @"command1 & command2");

2- Set the working directory of the process through ProcessStartInfo.

 var processInfo = new ProcessStartInfo("cmd.exe", @"your commands here ");
 processInfo.UseShellExecute = false;
 processInfo.WorkingDirectory = path;

3- Redirecting the input and output of the process. (Also done through the ProcessStartInfo).This is required when you like to send more input to the process, or when you want to get the output of the process

Also see this answer

Upvotes: 1

Related Questions