viernes, 26 de diciembre de 2014

C# - How to execute command lines and get the output (without opening the "cmd" window)

Hi again!

I want to share with you this code to execute commands and receive the answer/output without opening the "cmd" window.

Here you have the steps:
1) Create a VS C# project and add a textBox, a button and a listBox to the Form
2) Adapt the following code to your project:



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SandBox
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            if(textBox1.TextLength>0)
                executeCommand(textBox1.Text);
        }
        private void executeCommand(String commandR)
        {
            try
            {
                var proc = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName = "cmd.exe",
                        Arguments = "/c " + commandR,
                        UseShellExecute = false,
                        RedirectStandardOutput = true,
                        CreateNoWindow = true
                    }
                };
                updateStatusExecution("***COMMAND RECEIVED: " + commandR);
                updateStatusExecution("***ANSWER:");
                proc.Start();
                while (!proc.StandardOutput.EndOfStream)
                {
                    string line = proc.StandardOutput.ReadLine();
                    updateStatusExecution(line);
                }
            }
            catch (Exception e)
            {
                updateStatusExecution("***Error while executing '" + commandR + "'");
                updateStatusExecution("***Exception: '" + e.ToString());
                updateStatusExecution("***Stack Trace: '" + e.StackTrace.ToString());
            }
        }
        private void updateStatusExecution(String textR)
        {
            String currentDateTime = DateTime.Now.ToString(); ;
            listBox1.Items.Add(currentDateTime + " - " + textR);
        }
    }
}



3) Start (F5) and type a common command in the testBox to test.

Here's a screenshot of my code working.


Hope you had a wonderful Christmas and I wish you the best for 2015.
Regards!

Code Tricks.

No hay comentarios.:

Publicar un comentario