Introduction
I decided to write this article after being unable to find any example code on how to redirect console output to a file. There were examples of writing to a memory stream but I needed to output to a file because I was worried about the potential size of the memory stream required to do what I wanted. I had much help from my friend Armand so I would like to have him credited as a major contributor.
Background
I was experiencing errors when I used the redirection within the arguments sent to the process.
My code was written to back up a MySQL database using the tool mysqldump.exe but it should be easily changed to work with other console applications.
Using the Code
The sample is quite small. I have used comments to describe the process.
StreamWriter _outputStream;
private void OnDataReceived(object Sender, DataReceivedEventArgs e)
{
if ((e.Data != null)&&(_outputStream != null))
_outputStream.WriteLine(e.Data);
}
public void BackupLocalDatabase(string DatabaseName, string UserID, string Password,
string OutputFilename)
{
#region BackupLocalDatabase
string fnName = "BackupLocalDatabase";
try
{
_outputStream = new StreamWriter(OutputFilename);
try
{
string _args = string.Format(
" --databases {0} --user={1} --password={2} --hex-blob",
DatabaseName, UserID, Password);
ProcessStartInfo _info = new ProcessStartInfo("mysqldump");
_info.Arguments = _args;
_info.UseShellExecute = false;
_info.RedirectStandardError = true;
_info.RedirectStandardOutput = true;
Process _process = new Process();
_process.StartInfo = _info;
_process.OutputDataReceived += new DataReceivedEventHandler(OnDataReceived);
_process.Start();
_process.BeginOutputReadLine();
_process.WaitForExit();
}
finally
{
_outputStream.Flush();
_outputStream.Close();
}
}
catch (Exception e)
{
LogException(fnName, e);
throw e;
}
#endregion
}
History
2008-06-16 Written
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.