Monday, August 13, 2007

Running a batch in a hidden console window

[This was originally posted at http://timstall.dotnetdevelopersjournal.com/running_a_batch_in_a_hidden_console_window.htm]

.Net allows you to run a batch in a hidden console window using System.Diagnostics. You can specify a ProcessStartInfo object (really a strategy pattern), and then run the process. This is useful when trying to integrate to other programs that only provide a command line interface.

This simple utility method also provides the ability to log the console output to some log file (specified with strLogPath). I have a simple unit test simply as a stub to see how the code is called. In this case, I call the "test.bat" file, passing in a single param "abc", ask the calling code to wait until the batch finishes, and then log it to a given path.

 

    [TestMethod]
    public void TestDiagnostics_1()
    {
      RunHiddenExecutable(@"C:\Temp\test.bat", "abc", true, @"C:\temp\log.txt");
    }

    public static void RunHiddenExecutable(string strFileName, string strArguments, bool blnWaitForExit, string strLogPath)
    {
      bool blnOutputLogFile = true;
      if (strLogPath == null || strLogPath.Length == 0)
        blnOutputLogFile = false;
      System.Text.StringBuilder sb = new System.Text.StringBuilder();
      try
      {
        //run in process without showing dialog window:
        ProcessStartInfo psi = new ProcessStartInfo();
        psi.WindowStyle = ProcessWindowStyle.Hidden;
        psi.CreateNoWindow = true;    //Need to include this for Executable version (appears not to be needed if UseShellExecute=true)
        psi.FileName = strFileName;
        psi.Arguments = strArguments;
        psi.UseShellExecute = false;
        psi.RedirectStandardOutput = true;

        Process p = System.Diagnostics.Process.Start(psi);
        sb.Append(p.StandardOutput.ReadToEnd());

        if (blnWaitForExit)
          p.WaitForExit();

      }
      catch (Exception ex)
      {
        sb.Append("Exception Occured:\r\n");
        sb.Append(ex.ToString());
        throw;
      }
      catch
      {
        sb.Append("A non-CLSCompliant exception was thrown.");
        throw;
      }
      finally
      {
        //Implement - log this however you want
        //if (blnOutputLogFile)
        //  Write out file (sb.ToString(), strLogPath);
      } //end of try

    } //end of method

 

See also: How to send the Console output to a string

 


Living in Chicago and interested in working for a great company? Check out the careers at Paylocity.

 

No comments:

Post a Comment