Call Executable from C# Program

I had a requirement where in i should call an executable to find out all files that are getting modified/created while in run my application. I had to work on windows so chose to write a program in Dotnet which does that.

Here is the sample code which does that

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Threading;

namespace MediaController.Controller
{
    class MediaController
    {

        static void Main()
        {
            execCommand(@"C:\development\Ashwin\Streaming\FindModified\DirectoryChangeListener.exe");
        }

        public void execBasicCommand(string command)
        {
            //
            // Setup the process with the ProcessStartInfo class.
            //
            ProcessStartInfo start = new ProcessStartInfo();
            start.FileName = @"C:\development\Ashwin\Streaming\FindModified\DirectoryChangeListener.exe"; // Specify exe name.
            start.UseShellExecute = false;
            start.RedirectStandardOutput = true;
            //
            // Start the process.
            //
            using (Process process = Process.Start(start))
            {
                //
                // Read in all the text from the process with the StreamReader.
                //
                using (StreamReader reader = process.StandardOutput)
                {
                    string result = reader.ReadToEnd();
                    Console.Write(result);
                }
            }
        }

        public static void execCommand(string command)
        {
            try
            {
                Process process = new Process();
                ProcessStartInfo start = new ProcessStartInfo();
                // Set up process to redirect standard output and standard error to
                // a file.
                //process.StartInfo.FileName = @"C:\development\Ashwin\Streaming\FindModified\DirectoryChangeListener.exe"; ;
                process.StartInfo.FileName = command;
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError = true;
                //FileInfo ofi = new FileInfo("test.txt");
                //FileStream ofs = ofi.OpenWrite();
                //StreamWriter sw = new StreamWriter(ofs);
                WriteToTextWriterEventHandler wtsweh = new WriteToTextWriterEventHandler();
                DataReceivedEventHandler handler = wtsweh.HandleDataReceived;
                process.OutputDataReceived += handler;
                process.ErrorDataReceived += handler;
                //                
                process.Start();
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();

                process.WaitForExit();
                int processExitCode = process.ExitCode;
                process.Close();
                //sw.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
            }
        }

        // 
        private class WriteToTextWriterEventHandler
        {
            private TextWriter tw;

            public WriteToTextWriterEventHandler(TextWriter tw)
            {
                this.tw = tw;
            }

            public WriteToTextWriterEventHandler()
            {
                //this.tw = tw;
            }

            public void HandleDataReceived(object sendingProcess,
               DataReceivedEventArgs outLine)
            {
                // Collect the sort command output.
                if (!String.IsNullOrEmpty(outLine.Data))
                {
                    //tw.Write(Environment.NewLine + outLine.Data);
                    Console.WriteLine(outLine.Data);
                }
            }
        }

        /// 
        /// Executes a shell command synchronously.
        /// 
        /// string command
        /// string, as output of the command.
        public void ExecuteCommandSync(object command)
        {
            try
            {
                // create the ProcessStartInfo using "cmd" as the program to be run,
                // and "/c " as the parameters.
                // Incidentally, /c tells cmd that we want it to execute the command that follows,
                // and then exit.
                System.Diagnostics.ProcessStartInfo procStartInfo =
                    new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);

                // The following commands are needed to redirect the standard output.
                // This means that it will be redirected to the Process.StandardOutput StreamReader.
                procStartInfo.RedirectStandardOutput = true;
                procStartInfo.UseShellExecute = false;
                // Do not create the black window.
                procStartInfo.CreateNoWindow = true;
                // Now we create a process, assign its ProcessStartInfo and start it
                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                proc.StartInfo = procStartInfo;
                proc.Start();
                // Get the output into a string
                string result = proc.StandardOutput.ReadToEnd();
                // Display the command output.
                Console.WriteLine(result);
            }
            catch (Exception objException)
            {
                // Log the exception
            }
        }

        /// 
        /// Execute the command Asynchronously.
        /// 
        /// string command.
        public void ExecuteCommandAsync(string command)
        {
            try
            {
                //Asynchronously start the Thread to process the Execute command request.
                Thread objThread = new Thread(new ParameterizedThreadStart(ExecuteCommandSync));
                //Make the thread as background thread.
                objThread.IsBackground = true;
                //Set the Priority of the thread.
                objThread.Priority = ThreadPriority.AboveNormal;
                //Start the thread.
                objThread.Start(command);
            }
            catch (ThreadStartException objException)
            {
                // Log the exception
            }
            catch (ThreadAbortException objException)
            {
                // Log the exception
            }
            catch (Exception objException)
            {
                // Log the exception
            }
        }
    }

}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s