51365

View Output in a Batch (.bat) file from C# code

Question:

I have an c# code to execute the batch file. I want to show the information in the bat file in the command prompt. Here is my new edited c# code:

namespace CheckTime { class Program { static void Main(string[] args) { Program Obj = new Program(); int greetingId; int hourNow = System.DateTime.Now.Hour; if (hourNow < 12) greetingId = 0; else if (hourNow < 18) greetingId = 1; else greetingId = 2; System.Environment.ExitCode = greetingId; Obj.StartBatchFile(greetingId); } void StartBatchFile(int Gretting) { var p = new Process(); p.StartInfo.FileName = "cmd.exe"; p.StartInfo.Arguments = string.Format(@"/C D:\Nimit Joshi\Visual Studio 2013\CheckTime\CheckTime\Demo1.bat {0}", Gretting); p.OutputDataReceived += ConsumeData; try { p.Start(); p.WaitForExit(); } finally { p.OutputDataReceived -= ConsumeData; } } private void ConsumeData(object sender, DataReceivedEventArgs e) { Console.WriteLine(e.Data); } }

}

Following is my Demo1.bat file:

@echo off :: Use %1 to get the first command line parameter goto Greeting%1% :Greeting echo You have no entered a greeting. goto end :Greeting0 echo Good Morning goto end :Greeting1 echo Good Afternoon goto end :Greeting2 echo Good Evening goto end :end

It is always showing You have no entered a greeting

Answer1:

Use the <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx" rel="nofollow">Process.OutputStream</a> or listen to the <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.process.outputdatareceived.aspx" rel="nofollow">Process.OutputDataReceived</a> event.

Example:

private void ConsumeData(object sendingProcess, DataReceivedEventArgs outLine) { if(!string.IsNullOrWhiteSpace(outLine.Data)) Console.WriteLine(outLine.Data); } p.StartInfo.RedirectStandardOutput = true; p.StartInfo.UseShellExecute = false; p.StartInfo.CreateNoWindow = true; p.OutputDataReceived += ConsumeData; try { p.Start(); p.BeginOutputReadLine(); p.WaitForExit(); } finally { p.OutputDataReceived -= ConsumeData; }

The batch file should be rewritten to not cause an infinite loop.

@echo off :: Use %1 to get the first command line parameter goto Greeting%1% :Greeting echo You have no entered a greeting. goto end :Greeting0 echo Good Morning goto end :Greeting1 echo Good Afternoon goto end :Greeting2 echo Good Evening goto end :end

C#

void StartBatchFile(int arg) { var p = new Process(); p.StartInfo.FileName = "cmd.exe"; p.StartInfo.Arguments = string.Format(@"/C C:\temp\demo.bat {0}", arg); p.StartInfo.RedirectStandardOutput = true; p.StartInfo.UseShellExecute = false; p.StartInfo.CreateNoWindow = true; p.OutputDataReceived += ConsumeData; try { p.Start(); p.BeginOutputReadLine(); p.WaitForExit(); } finally { p.OutputDataReceived -= ConsumeData; } }

Answer2:

You return (i.e. exit your program) before you call anotherMethod().

And that's good, otherwise you'd have an infinite loop of the .exe staring the .bat.

Recommend

  • Is there any way to create symbolic link in WIX installer?
  • How to grab parent process standard output?
  • c# run process on non-admin right
  • EJB stateless - Private members initialisation
  • How to set repeating alarm using setExact and how to cancel the same?
  • Best way to display non-public images in a rails view
  • Start another EXE in Managed Code
  • Allowing my app users to post tweets from a single account
  • Timer once a minute on the minute
  • 1º Day of Daylight Saving Time Java and JS showing a different behavior
  • View Paypal shopping cart contents on my site
  • Timeout a query
  • Put value at centre of bins for histogram
  • How to skip require in ruby?
  • VSCode change debug shell to bash on windows
  • Error processing multiple files
  • aapt.exe'' finished with non-zero exit value 1
  • Saving image to sd with current date and time in name doesn't work
  • how to upload multiple files in c# windows application
  • Tamper-proof configuration files in .NET?
  • Code in Job's Script Block after Start-Process Does not Execute
  • How can I sort a a table with VBA with given text condition?
  • Yii2: Config params vs. const/define
  • How to install a .deb file on a jailbroken iphone programmatically?
  • Handling un-mapped Rest path
  • Running a C# exe file
  • 0x202A in filename: Why?
  • How to delete a row from a dynamic generate table using jquery?
  • using HTMLImports.whenReady not working in chrome
  • Understanding cpu registers
  • How do I configure my settings file to work with unit tests?
  • Authorize attributes not working in MVC 4
  • EntityFramework adding new object to nested object collection
  • reshape alternating columns in less time and using less memory
  • costura.fody for a dll that references another dll
  • Observable and ngFor in Angular 2
  • UserPrincipal.Current returns apppool on IIS
  • Converting MP3 duration time
  • java string with new operator and a literal
  • How do I use LINQ to get all the Items that have a particular SubItem?