Click here to Skip to main content
Click here to Skip to main content

Redirecting Text Output to a File from a Console Application

By , 17 Jun 2008
 

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;

// Called asynchronously with a line of data
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
        {
            // --databases to force CREATE DATABASE
            // --hex-blob to force output of blobs as hex strings
            string _args = string.Format(
                " --databases {0} --user={1} --password={2} --hex-blob",
                DatabaseName, UserID, Password);

            // Info object
            ProcessStartInfo _info = new ProcessStartInfo("mysqldump");
            _info.Arguments = _args;
            _info.UseShellExecute = false;
            _info.RedirectStandardError = true;
            _info.RedirectStandardOutput = true;

            // Process object
            Process _process = new Process();
            _process.StartInfo = _info;

            // Set up the event handler to call back with
            // each line of output
            _process.OutputDataReceived += new DataReceivedEventHandler(OnDataReceived);
            _process.Start();
            _process.BeginOutputReadLine();
            _process.WaitForExit();

            //TODO error checks here

        }
        finally
        {
            _outputStream.Flush();
            _outputStream.Close();
        }
    }
    catch (Exception e)
    {
        LogException(fnName, e);
        throw e;
    }
#endregion
}// function

History

2008-06-16 Written

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

czeshirecat
United Kingdom United Kingdom
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionCould you please improve your article?memberCuchuk Sergey23 Jun '08 - 1:11 
I worked with that and see that you missed something:
 
often programs are used on some local environments and produces output in non-standard encoding(for example when 7-zip processes files with russian characters it produces output that should be converted)
 
so could you investigate such problems and update your code by adding convertion from one encoding to another?
GeneralInterestingmembermerlin98118 Jun '08 - 3:50 
Interesting idea. You might want to add some thread safety to the writing of the file, though. If you have two events raised too closely together, they might both try to write at the same time (since each event is raised in a new thread). Also, you need to have a way to gracefully close and dispose of the file stream once you are done.
GeneralRe: InterestingmemberCuchuk Sergey23 Jun '08 - 1:12 
try using clause
GeneralRe: Interestingmemberwizardzz11 Dec '12 - 11:00 
I just thought the same thing while reading the article.
QuestionWhat problems?memberPIEBALDconsult17 Jun '08 - 6:01 
"
I was experiencing errors when I used the redirection within the arguments sent to the process.
"
 
What sorts of problems? With what code? Example?
QuestionAm I missing something obvious?memberHumble Programmer17 Jun '08 - 5:52 
Doesn't standard command line redirection do the same thing?
myprogram myarguments > myoutputfile
 
See TechNet[^] for details.
 
Cheers!
Humble Programmer
,,,^..^,,,

AnswerRe: Am I missing something obvious?memberCuchuk Sergey23 Jun '08 - 1:08 
Yes, you do:
 
this variant with redirecting output is bad because it causes problems with other language encodings: it's problemmatically to find the source and target encoding before using redirected message to see the proper unicode characters(not abrakadabra)

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130516.1 | Last Updated 17 Jun 2008
Article Copyright 2008 by czeshirecat
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid