1

I'm trying to get a button, run a process in background, read the output and put it on a TextBox.

This question helped me to read the output. But I need to dinamically read the output and with this solution it only shows the full output once the process has exited.

my code is like this:

private void button7_Click(object sender, EventArgs e)
{

    Process startInfo = new Process
    {
        StartInfo = new ProcessStartInfo
        {
            FileName = "cmd.exe",
            Arguments = "/c \"ping www.google.com\"",

            UseShellExecute = false,
            RedirectStandardOutput = true,
            CreateNoWindow = true

        }
    };
    startInfo.EnableRaisingEvents = true;
    startInfo.OutputDataReceived += ProcessDataHandler;
    startInfo.ErrorDataReceived += ProcessDataHandler;

    m_sbText = new System.Text.StringBuilder(1000);

    startInfo.Exited += new EventHandler(this.myProcess_Exited);                

    if (MessageBox.Show("Are you sure?, this may take severa minutes", "Export DAT", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
    {
        commonMethods.logMessage(string.Concat("Exportar DAT: ", file, " ", arguments), null);
        try
        {
            startInfo.Start();
            startInfo.BeginOutputReadLine();
            while (!startInfo.HasExited)
            {
                System.Threading.Thread.Sleep(500);
                Application.DoEvents();
            }
            this.textBox1.Text = m_sbText.ToString();
        }
        catch (Exception exception)
        {
            commonMethods.logMessage(string.Concat("Error exporting DAT: "), exception.InnerException);
        }

    }
}

private static void ProcessDataHandler(object sendingProcess, DataReceivedEventArgs outLine)
    {
        // Collect the net view command output. 
        if (!String.IsNullOrEmpty(outLine.Data))
        {
            // Add the text to the collected output.
            m_sbText.AppendLine(outLine.Data);
        }
    }

Thanks

Lasmaty07
  • 21
  • 6

0 Answers0