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()
            //string cmdCommand = "COPY H:\\nbb.txt F:";
        public void ExecuteCommandSync()
            string cmdCommand = "COPY H:\\nbb.txt F:";
                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;
                string result = proc.StandardOutput.ReadToEnd();
                lblMessage.Text = result;
            catch (Exception objException)

Do not forget to leave your comments below.

1 comment:

  1. I have read your blog its very attractive and impressive. I like it your blog.

    Java Online Training Java EE Online Training Java EE Online Training Java 8 online training Core Java 8 online training

    Java Online Training from India Java Online Training from India Core Java Training Online Core Java Training Online Java Training InstitutesJava Training Institutes