Click here to Skip to main content
15,889,863 members
Articles / Programming Languages / C#
Tip/Trick

C# Programm to Run Multi Command on Cmd while Your Application Run

Rate me:
Please Sign up or sign in to vote.
2.56/5 (5 votes)
20 Sep 2015CPOL2 min read 20.4K   305   9   6
How to run multi commands on Cmd on One process and once and Sync .

Introduction

in some times devolpers need to run multiline commands twards the windwos cmd to do Some work they need,this approach might be used in a wide area of applications , now as my effort in search i didn't see  such this approach so if there is some approach more reliable and easier than this so you can use it .

So this is the sample output for our application : 

Image 1

 

Background

Some time before , i searched about a solutions to do this task but what i found wasn't suitable  so i search and search , Accidentally i see some files that it's extention called "cmd" i think in some simple ways to do it by creating a file with "cmd" extention and run it ASync with your app , you would do this through your code  .

in the next section i will explain this simple way with example  .

Using the code

First thing you should think about it is to creating the file if not exist , if file exist and your Command parameter changed , you would reset the content of the file .

The best way to do all this is the use of File.WriteAllText(string FileName ,string Content) ; so for Synchronization Problems before write any content to the file first we will check that there is no other (read / write ) operations runs twards the file then we will use this Methode :

IsFileLocked(FileInfo file) 
C#
protected static bool IsFileLocked(FileInfo file)
      {
            FileStream stream = null;
            try
            {
                stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
            }
            catch (IOException)
            {
                return true;
            }
            finally
            {
                if (stream != null)
                    stream.Close();
            }
            return false;
       }

then now we can start writting our Content Line by Line to the file using this Code : 

WriteContentToFile(string cmdfilename , string[] lines)
C#
 private void WriteContentToFile(string Cmdfilename , string[] lines)
        {
        retray:
            if (!IsFileLocked(new FileInfo(Cmdfilename)))
            {   
                    string content = "";
                    foreach (string str in lines)
                    {
                        content += str + "\n";
                    }
                    File.WriteAllText(Cmdfilename, content);
            }
            else
            {
                goto retray;
            }
        }
After this we need to methode to run the file to be executed on the cmd first we will provide methode to run it in seperated process after this we will load this methode ASynchronasily by a thread within the current programm process .
 
RunCMDScript(object scriptPath)
 
C#
 private void RunCMDScript(object scriptPath)
        {
            System.Diagnostics.ProcessStartInfo procStartInfo = 
                                       new System.Diagnostics.ProcessStartInfo(scriptPath.ToString());
            // Now we create a process, assign its ProcessStartInfo and start it
            System.Diagnostics.Process proc = new System.Diagnostics.Process();
            proc.StartInfo = procStartInfo;
            proc.Start();
        }
After this we need to path the array of lines and Call the process of the file .
as example we will use this sample command to Test our work : 
cd / 
C:
dir
cd "Program Files"
dir
pause
 
So we will use this method to do this : 
RunMultiLineCommand()
C#
public void RunMultiLineCommand()
        {
            char c = '"';
            string[] cmdarr = new string[] 
           { "cd /", "C:", "dir", string.Format("cd {0}Program Files{0}" ,c ) , "dir", "pause" };
            string filename= System.AppDomain.CurrentDomain.BaseDirectory + "testcmd.cmd";
            WriteContentToFile(filename,cmdarr);
            Thread objThread = new Thread(new ParameterizedThreadStart(RunCMDScript));
            objThread.IsBackground = true;
            objThread.Priority = ThreadPriority.AboveNormal;
            objThread.Start(filename);
        }
After allof this i hope that i provide thing that make your work more easier you Can dwonload the attached example fill free to ask about any thing on this mail {khairymohamed983@gmail.com}
Quote:

Note : it preared to create the file in your application directory For First Time .

 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Egypt Egypt
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralIt is a nice work , Good luck Pin
Amr El-Hezzawy30-Sep-15 9:36
Amr El-Hezzawy30-Sep-15 9:36 
General[My vote of 2] General code comments Pin
John Brett20-Sep-15 22:34
John Brett20-Sep-15 22:34 
GeneralRe: General code comments Pin
Khairy Mohammed21-Sep-15 15:10
Khairy Mohammed21-Sep-15 15:10 
QuestionGreat Tip, but your english.. Pin
Jethro Daniel20-Sep-15 16:11
Jethro Daniel20-Sep-15 16:11 
AnswerRe: Great Tip, but your english.. Pin
Khairy Mohammed21-Sep-15 15:11
Khairy Mohammed21-Sep-15 15:11 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.