using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using Yaulw.File; namespace Yaulw.Other { /// /// Usefull for quickly generating a .bat file and executing it (without a command window) /// public static class CMDexecute { #region Public Static Methods /// /// Executes the passed in command on the command line * No Command Window Created * /// /// a command-line command /// true to wait till process ends, false otherwise /// If true, will set "RunAs" For the Process, to Run as Administrator public static void cmd(string command, bool bWait = true, bool bRunAs = false) { FileWriter fileW = new FileWriter(String.Empty, "bat"); fileW.DeleteFile(); fileW.WriteLineUTF8(command); execBatFile(fileW.FileNameNPath, bWait, bRunAs); fileW.DeleteFile(); } /// /// Executes the passed in commands on the command line * No Command Window Created * /// /// command-line commands /// true to wait till process ends, false otherwise /// If true, will set "RunAs" For the Process, to Run as Administrator public static void cmd(string[] commands, bool bWait = true, bool bRunAs = false) { FileWriter fileW = new FileWriter(String.Empty, "bat"); fileW.DeleteFile(); foreach (string command in commands) fileW.WriteLineUTF8(command); execBatFile(fileW.FileNameNPath, bWait, bRunAs); fileW.DeleteFile(); } #endregion #region Private Static Helpers /// /// Executes the Batch file via CMD.exe, by starting the CMD.exe Process with no Window /// /// File (.bat) scrip to execute /// true to wait till process ends, false otherwise private static void execBatFile(string FileNameNPath, bool bWait = true, bool bUseRunAs = false) { if (!String.IsNullOrEmpty(FileNameNPath) && System.IO.File.Exists(FileNameNPath)) { //The "/C" Tells Windows to Run The Command then Terminate string strCmdLine = "/C " + '\"' + FileNameNPath + '\"'; string WindowsSystem32Folder = System.Environment.GetFolderPath(Environment.SpecialFolder.System); System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo((WindowsSystem32Folder + "\\" + "CMD.exe"), strCmdLine); //startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; startInfo.CreateNoWindow = true; startInfo.UseShellExecute = false; startInfo.WorkingDirectory = Path.GetDirectoryName(FileNameNPath); if (bUseRunAs) startInfo.Verb = "runas"; // Start the Cmd.exe Process System.Diagnostics.Process p1; p1 = System.Diagnostics.Process.Start(startInfo); if(bWait) p1.WaitForExit(); } } #endregion } }