Wednesday 10 June 2015

How to Execute System's Internal and External Commands using C# program



In this blog will learn how to execute System or DOS Internal and External using C# programming.              
                        (We are not learning what is an Internal and External commands)

-                   For that we need two basic things – an installed .NET Framework and a text editor.
-                   We need the text editor to write and edit the C# code and the .NET Framework to compile and execute it.

1] .NET Framework:-
 By default, the .NET Framework is installed along with Windows, but in old Windows versions it could be missing. To install the .NET Framework, we must download it from Microsoft’s website (http://download.microsoft.com). It is best if we download and install the latest version.

2] Text Editor
The text editor is used to write the source code of the program and to save it in a file.
We can use Windows’ built-in Notepad.

Now,
Changing the System Paths in Windows
-                   If you are writing a code in text editor then you must set the path but there is no need to set a path for visual studio IDE.
Open control panel->system->Advanced System Setting->Advanced-> Environment Variable




-                   Click on New button of System variable panel and enter the Variable Name as Path and Variable value as  ” C:\Windows\Microsoft.NET\Framework64\v4.0.30319;” semicolon (;) is compulsory.

Note:
This path could vary depending on the .NET framework version installed on your machine.


-                   For the compiling C# program we need C-Sharp Compiler, CSC is Command for compiling a C# program.

-                   Before setting the environment variable it shows the following error.



-After Setting the environment variable it shows the following message



Now, we are going to actual our program
-                   First we will learn how to execute a simple command in C# program
-                   Following code write in notepad editor and save it as MyProcess.cs



_______________________________________________________________________________________________
namespace MyProcess
{
    class Program
    {
        static void Main(string[] args)
        {
            System.Diagnostics.Process.Start("notepad");
        }
    }
}
_______________________________________________________________________________________________

For compiling above program we use CSC command like,
CSC MyProcess.cs
-                   This command generate MyProcess.exe file
-                    For run above .exe write only name and hit the enter
MyProgram.exe (and hit the enter)

Above program will open the notepad process.
Note: -
 Each command after executing become process that’s why there is a process class

1.       Now we will learn how to execute an external commands.
-                   Following program showing how to execute an external commands.


_______________________________________________________________________________________________

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SystemCommand
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Title="Command using C# !!!";
            int n = 0;
            do
            {

                Console.WriteLine("1 : Wordpad");
                Console.WriteLine("2 : Notepad");
                Console.WriteLine("3 : Ms-Powerpoint");
                Console.WriteLine("4 : Ms-Excel");
                Console.WriteLine("5 : Ms-Access");
                Console.WriteLine("6 : Ms-Word");
                Console.WriteLine("7 : Ms-Pint");
                Console.WriteLine("8 : Exit");

                n = Convert.ToInt32(Console.ReadLine());

                switch(n)
                {
                    case 1:
                        System.Diagnostics.Process.Start("wordpad");
                        break;
                    case 2:
                        System.Diagnostics.Process.Start("notepad");
                        break;
                    case 3:
                        System.Diagnostics.Process.Start("powerpnt");
                        break;
                    case 4:
                        System.Diagnostics.Process.Start("excel");
                        break;
                    case 5:
                        System.Diagnostics.Process.Start("msaccess");
                        break;
                    case 6:
                        System.Diagnostics.Process.Start("winword");
                        break;
                    case 7:
                        System.Diagnostics.Process.Start("mspaint");
                        break;
                    case 8:
                       
                        System.Environment.Exit(0);
                        break;
                    default :
                        Console.WriteLine("Wrong Choice!!");
                        break;
                }
                Console.Clear();
            } while (n != 0);
           
        }
    }
}
_______________________________________________________________________________________________

2.       Now we will learn how to execute an internal commands.
-                   Following program showing how to execute an internal commands.
_______________________________________________________________________________________________
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DosCommandWithRedirection
{
    class Program
    {
        static void Main(string[] args)
        {
            // start the Command Prompt
            ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd.exe");

            //join the input pipe to Command Prompt
            processStartInfo.RedirectStandardInput = true;

            //join the output pipe to our program(process)
            processStartInfo.RedirectStandardOutput = true;
            processStartInfo.UseShellExecute = false;
            Process process = Process.Start(processStartInfo);

            if (process != null)
            {
                //create a folder with a name 'Ashutosh'
                process.StandardInput.WriteLine(@"mkdir D:\Ashutosh");

                //write all  information about folder into 'ashu.txt'
                process.StandardInput.WriteLine(@"dir>D:/Ashutosh/ashu.txt");
               
                //print on Console
                process.StandardInput.WriteLine("echo Thanks..");

                // line added to stop process from hanging on ReadToEnd()
                process.StandardInput.Close();

                // all output of console copy into string
                string outputString = process.StandardOutput.ReadToEnd();

                //print that output
                Console.WriteLine(outputString);

                //hold the console screen
                Console.ReadKey();

            }

        }
    }
}
________________________________________________________________________________________________________
Explanation:
-          StandardInput class is use for giving the command to Command Prompt and WriteLine() method write the command on Command Prompt
-          StandardOutput class is use for taking the output from Command Prompt and ReadToEnd() method is use for read the output to the end and written into string

Note:-
We can perform all tasks using above program whatever we can perform using Command Prompt.









                                                                                                                           -Created By Ashutosh Jagtap,
                                   For any grievance mail us on     
                                                                                                         ashujagtap333@gmail.com