How to get Conole output information in my winform program?

  • Thread starter Thread starter Liren Zhao
  • Start date Start date
L

Liren Zhao

I use some "Console.WriteLine(some strings here)" to
display some
debug information in my winform program.
How can I get the information in my programe or same them
in a text file ?
 
Liren Zhao said:
I use some "Console.WriteLine(some strings here)" to
display some
debug information in my winform program.
How can I get the information in my programe or same them
in a text file ?

I'm not saying the following is a clean implementation but it works. The
code depends on the value of the String output. If output is empty all data
is written to the console otherwise the console is redirected to the file
specified by output :

/*******************************************/
/* Output redirector */
StreamWriter sw = null ;
TextWriter tmp = Console.Out;
if (output != "")
{
tmp = Console.Out;
FileStream fs = new FileStream(output, FileMode.OpenOrCreate,
FileAccess.Write);
sw = new StreamWriter(fs);
Console.SetOut(sw);
}

// do your work just as normal
Console.WriteLine("redirection test");

/* Output redirector clean up */
if (output != "")
{
Console.SetOut(tmp);
sw.Close();
}
/*******************************************/

Yves
 
Thanks for your replay.
I'm a jackaroo in c#,would you give me a full code?

And what is output in your code?
 
Liren Zhao said:
Thanks for your replay.
I'm a jackaroo in c#,would you give me a full code?

It is a full code ... At the bottom of this message you'll find it inside a
console application but nothing much changed. Just comment out the output
definition you don't want to use to test both cases.
And what is output in your code?

A String like i stated just above the code in the previous message ...

using System;
using System.IO;
namespace softtech.redirection
{
class redir
{
[STAThread]
static void Main(string[] args)
{
String output = @"c:\test.txt"; // output redirection to the file
//String output = ""; // normal output to stdout

StreamWriter sw = null ;
TextWriter tmp = Console.Out;

if (!output.Equals(""))
{
tmp = Console.Out;
FileStream fs = new FileStream(output,
FileMode.OpenOrCreate,FileAccess.Write);
sw = new StreamWriter(fs);
Console.SetOut(sw);
}

// do your work just as normal
// the program will write to the correct spot
Console.WriteLine("redirection test");

/* Output redirector clean up */
if (!output.Equals(""))
{
Console.SetOut(tmp);
sw.Close();
}
}
}
}
 
Back
Top