Friday, February 20, 2015

How to run cmd command in c#

Today I'm going to discuss on how to Execute cmd commands in C#. This way, you can easily run cmd commands.Here I used COPY H:\\nbb.txt F:  this command to copy a file (nbb.txt) from H: drive to F: drive.
 


 
Create a New project and add the following code to the Form1.cs class.


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

namespace ExecuteCMDCommand
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            ExecuteCommandSync();
            //string cmdCommand = "COPY H:\\nbb.txt F:";
            //ExecuteCommandSync(txtCommand.Text);
        }
        public void ExecuteCommandSync()
        {
            string cmdCommand = "COPY H:\\nbb.txt F:";
            try
            {
                System.Diagnostics.ProcessStartInfo procStartInfo =
                    new System.Diagnostics.ProcessStartInfo("cmd", "/c " + cmdCommand);

                procStartInfo.RedirectStandardOutput = true;
                procStartInfo.UseShellExecute = false;
                procStartInfo.CreateNoWindow = true;
                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                proc.StartInfo = procStartInfo;
                proc.Start();
                string result = proc.StandardOutput.ReadToEnd();
                lblMessage.Text = result;
                Console.WriteLine(result);
            }
            catch (Exception objException)
            {
            
            }
        }
    }
}

Do not forget to leave your comments below.
 

No comments:

Post a Comment