Thursday, August 23, 2012

Execute Batch File Using c#.net


   private void ExecuteBatch(string strFilePath)
        {
            string fullPath = Directory.GetParent(strFilePath).FullName;
            // Create the ProcessInfo object
            System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("cmd.exe");
            psi.UseShellExecute = false;
            psi.RedirectStandardOutput = true;
            psi.RedirectStandardInput = true;
            psi.RedirectStandardError = true;
            psi.WorkingDirectory = fullPath;// strPath;

            // Start the process
            System.Diagnostics.Process proc = System.Diagnostics.Process.Start(psi);
            // Open the batch file for reading
            System.IO.StreamReader strm = System.IO.File.OpenText(strFilePath);
            // Attach the output for reading
            System.IO.StreamReader sOut = proc.StandardOutput;
            // Attach the in for writing
            System.IO.StreamWriter sIn = proc.StandardInput;
            // Write each line of the batch file to standard input
            while (strm.Peek() != -1)
            {
                sIn.WriteLine(strm.ReadLine());
            }
            strm.Close();
            // Exit CMD.EXE
            string stEchoFmt = "# {0} run successfully. Exiting";
            sIn.WriteLine(String.Format(stEchoFmt, strFilePath));
            sIn.WriteLine("EXIT");
            // Close the process
            proc.Close();
            //this.AfterInstall += new InstallEventHandler(ServiceInstaller_AfterInstall);
            sIn.Close();
            sOut.Close();
        }

No comments: