Sunday, July 27, 2008

Reading the output of a process


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;


namespace test
{
public partial class Form1 : Form
{
Process process = new Process();


public Form1()
{
InitializeComponent();

process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.FileName = "C:/CSharp/SQLite/sqlite3.exe";
process.StartInfo.Arguments = "a.db3";
}

private void button1_Click(object sender, EventArgs e)
{


process.Start();
//process.BeginOutputReadLine();

process.OutputDataReceived += new DataReceivedEventHandler(process_OutputDataReceived);
process.ErrorDataReceived += new DataReceivedEventHandler(process_ErrorDataReceived);
//process.BeginErrorReadLine();
process.BeginOutputReadLine();
}

void process_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
//log.Error(e.Data);
}

void process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
//log.Info(e.Data);
this.AddText(e.Data);

}

delegate void AddTextCallback(string text);

private void AddText(string text)
{
if (this.label1.InvokeRequired)
{
AddTextCallback d = new AddTextCallback(AddText);
this.Invoke(d, new object[] { text });
}
else
{
this.label1.Text += text + Environment.NewLine;

}
}


}
}

No comments: