I have a program which outputs various results onto a command line console.
How do I save the output to a text file using a StreamReader
or other techniques?
System.Collections.Generic.IEnumerable<String> lines = File.ReadAllLines(@"C:\Test\ntfs8.txt");
foreach (String r in lines.Skip(1))
{
String[] token = r.Split(',');
String[] datetime = token[0].Split(' ');
String timeText = datetime[4];
String actions = token[2];
Console.WriteLine("The time for this array is: " + timeText);
Console.WriteLine(token[7]);
Console.WriteLine(actions);
MacActions(actions);
x = 1;
Console.WriteLine("================================================");
}
if (x == 2)
{
Console.WriteLine("The selected time does not exist within the log files!");
}
System.IO.StreamReader reader = ;
string sRes = reader.ReadToEnd();
StreamWriter SW;
SW = File.CreateText("C:\\temp\\test.bodyfile");
SW.WriteLine(sRes);
SW.Close();
Console.WriteLine("File Created");
reader.Close();
Using only configuration in your app.config:
For testing, you can use DebugView before running the program, then we can easily view all of the log messages.
References:
http://blogs.msdn.com/b/jjameson/archive/2009/06/18/configuring-logging-in-a-console-application.aspx http://www.thejoyofcode.com/from_zero_to_logging_with_system_diagnostics_in_15_minutes.aspx
Redirect Trace output to Console
Problem redirecting debug output to a file using trace listener
https://ukadcdiagnostics.codeplex.com/
http://geekswithblogs.net/theunstablemind/archive/2009/09/09/adventures-in-system.diagnostics.aspx
Try this example from this article - Demonstrates redirecting the Console output to a file
Try if this works:
For the question:
I would use
Console.SetOut
as others have mentioned.However, it looks more like you are keeping track of your program flow. I would consider using
Debug
orTrace
for keeping track of the program state.It works similar the console except you have more control over your input such as
WriteLineIf
.Debug
will only operate when in debug mode where asTrace
will operate in both debug or release mode.They both allow for listeners such as output files or the console.
-http://support.microsoft.com/kb/815788
do you want to write code for that or just use command-line feature 'command redirection' as follows:
app.exe >> output.txt
as demonstrated here: http://discomoose.org/2006/05/01/output-redirection-to-a-file-from-the-windows-command-line/ (Archived at archive.org)
EDIT: link dead, here's another example: http://pcsupport.about.com/od/commandlinereference/a/redirect-command-output-to-file.htm
Use
Console.SetOut
to redirect to aTextWriter
as described here: http://msdn.microsoft.com/en-us/library/system.console.setout.aspx