How to execute multiple commands (cmd) C #?

-1

Good people, I need an application that captures the input and output, so that after executing a command the same prompt is not closed.

Now I can execute commands and capture output in isolation. Here is the function I did:

public string Cmd(string comand)
    {
        cmd.StartInfo.FileName = "cmd.exe";
        cmd.StartInfo.Arguments = string.Format("/c {0}", comand);
        cmd.StartInfo.UseShellExecute = false;
        cmd.StartInfo.CreateNoWindow = true;
        cmd.StartInfo.RedirectStandardOutput = true;
        cmd.Start();

        string output = cmd.StandardOutput.ReadToEnd();
        if (output == "") { output = "Comando executado"; }
        return output;
    }
    
asked by anonymous 28.07.2018 / 03:24

1 answer

0

It's not perfect, it needs tweaking. I do not know if that's exactly what you need.

    static Process execCommand = new Process();
    static void Cmd2(string comando, string argumentos)
    {
        string saida = "";



        execCommand.StartInfo.FileName = comando;
        execCommand.StartInfo.UseShellExecute = false;
        //  execCommand.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        execCommand.StartInfo.Arguments = argumentos;
        execCommand.StartInfo.RedirectStandardOutput = true;
        try
        {
            execCommand.Start();
            saida = execCommand.StandardOutput.ReadToEnd();
            Console.WriteLine(saida);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }




    }

    static void IniciarCmd2(int numeroDeComandos)
    {
        string[] comandos = new string[numeroDeComandos];
        string[] argumentos = new string[numeroDeComandos];

        for (int i = 0; i < comandos.Length; i++)
        {
            Console.WriteLine("Digite o comando n#" + (i+1));
            comandos[i] = Console.ReadLine();
            Console.WriteLine("Digite o argumento n#" + (i+1));
            argumentos[i] = Console.ReadLine();
        }

        for (int i = 0; i < comandos.Length; i++)
        {
            Cmd2(comandos[i], argumentos[i]);

        }
    }
    static void Main(string[] args)
    {



        Console.WriteLine("Quantos comandos pretende executar?");


        IniciarCmd2(Convert.ToInt32(Console.ReadLine()));



        Console.Read();
    }
    
28.07.2018 / 23:05