Show Command Prompt Output with BackgroundWorker.B

2019-07-12 15:31发布

问题:

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!

回答1:

Since you have one of the following properties set to true, you'll get a blank black Window

RedirectStandardInput
RedirectStandardOutput
RedirectStandardError 

This 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

//obj.Activity = process.StandardOutput.ReadToEnd();

Unfortunately, this won't work unless you set RedirectStandardOutput to True so that your application would have the ability to read the output from the target batch file. Otherwise, the output will be empty

Example

private void RunBatch(CmdObj obj)
{
    var process = new Process();
    var startInfo = new ProcessStartInfo
    {
        FileName = obj.SrcFile,
        WindowStyle = ProcessWindowStyle.Normal,
        CreateNoWindow = false,
        RedirectStandardInput = true,
        RedirectStandardOutput = true, //This is required if we want to get the output
        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(); //Get the output from the target process
        obj.Error = process.StandardError.ReadToEnd();

    }
    catch (Exception ex)
    {
        obj.Exception = ex;
    }
    finally
    {
        process.Close(); //Terminate the process after getting what is required
    }
}

Notice that: UseShellExecute must be False in order to use RedirectStandardOutput

Thanks,
I hope you find this helpful :)



回答2:

Don't you need to call

 process.BeginErrorReadLine();
 process.BeginOutputReadLine();

after process starts? I had some problems without this if I remember right.



标签: c# cmd