I have a program that executes a batch file using an asynchronous background worker. Here is the code:
public static void Execute(CmdObj obj, bool batch)
{
CmdObj = obj;
var theWorker = new BackgroundWorker();
theWorker.RunWorkerCompleted += WorkerCompleted;
theWorker.WorkerReportsProgress = true;
if(batch)
{
theWorker.DoWork += WorkerBatchWork;
}else{
theWorker.DoWork += WorkerCommandWork;
}
theWorker.RunWorkerAsync();
}
private static void WorkerBatchWork(object sender, DoWorkEventArgs e)
{
RunBatch(CmdObj);
}
private static void WorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
var temp = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
if (temp != null)
ProgramPath = temp.Substring(6);
WriteLog(CmdObj.Activity, false);
WriteLog(CmdObj.Error, true);
CmdObj.TheButton.Enabled = true;
}
private static void RunBatch(CmdObj obj)
{
var process = new Process();
var startInfo = new ProcessStartInfo
{
FileName = obj.SrcFile,
WindowStyle = ProcessWindowStyle.Normal,
CreateNoWindow = false,
RedirectStandardInput = true,
RedirectStandardOutput = false,
RedirectStandardError = true,
UseShellExecute = false
};
try
{
if (!obj.SrcFile.ToLower().Trim().EndsWith(".bat"))
throw new FileLoadException("Not a valid .bat file",obj.SrcFile);
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();
//obj.Activity = process.StandardOutput.ReadToEnd();
obj.Error = process.StandardError.ReadToEnd();
}
catch (Exception ex)
{
obj.Exception = ex;
}
finally
{
process.Close();
}
}
class CmdObj
{
public string Command { get; set; }
public string SrcFile { get; set; }
public string Activity { get; set; }
public string Error { get; set; }
public Exception Exception { get; set; }
public Button TheButton { get; set; }
}
So when I run this program and choose a batch file to execute, I get a blank CMD window. Is there some way to show the output in the CMD window when my program executes the batch file? Alternatively, if I could have the CMD output sent to a textbox or some other control (in real-time), that would work as well.
Thanks!
Since you have one of the following properties set to
true
, you'll get a blank black WindowThis will actually happen because you've told your application to receive/send the output/input from the target process
I see that you were trying to get the output from the batch file using this line
Unfortunately, this won't work unless you set
RedirectStandardOutput
toTrue
so that your application would have the ability to read the output from the target batch file. Otherwise, the output will be emptyExample
Notice that:
UseShellExecute
must beFalse
in order to useRedirectStandardOutput
Thanks,
I hope you find this helpful :)
Don't you need to call
after process starts? I had some problems without this if I remember right.