How to call .bat file from .NET?

B

Bright

Hi All,

I want to execute a .bat file and get the output from console using C# in a
window application, the .bat file includes the java classpath and other
environment setting, can anyone know how I can do that?

Thanks in advance,
Bright
 
G

Guest

Hi

You can use System.Diagnostics.Process class from .Net Framework library.
You shold write something like that:

Process batch = new Process();
batch.StartInfo.FileName = "YourBatchFileName.bat";
batch.StartInfo.Arguments = "";
batch.StartInfo.UseShellExecute = true;
batch.Start();
batch.WaitForExit();

Good luck!
 
K

Kai Brinkmann [MSFT]

This will work. But if you want to intercept the process' output (rather
than having it appear in the console window), you need to do a couple of
other things.

....
batch.StartInfo.UseShellExecute = false;
batch.StartInfo.RedirectStandardOutput = true;
....
batch.Start();
string sOutput = batch.StandardOutput.ReadToEnd();
batch.WaitForExit();

The string sOuput now holds the process' standard output. Note that you must
set UseShellExecute to false in order to redirect stdout (or stderr, for
that matter). Make sure to call ReadToEnd() before WaitForExit(). Otherwise,
you could cause deadlock if the process output fills the buffer. In that
case, the child process would wait for the parent to read the buffer while
the parent is waiting for the child to end.

You can redirect the other standard streams in the same manner. Just be
aware that you cannot read BOTH stderr and stdout. This will also cause
deadlock, because the parent cannot read from stderr until it's done reading
from stdout. But it will not read stdout until the process is finished. If
you need to read both streams, you will have to use separate threads to do
so.

I hope this helps.
--
Kai Brinkmann [MSFT]

Please do not send e-mail directly to this alias. This alias is for
newsgroup purposes only.
This posting is provided "AS IS" with no warranties, and confers no rights.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top