如何将Console.WriteLine输出保存到文本文件?

我有一个程序输出各种结果到命令行控制台。

如何通过Stream Reader或其他方法将输出保存到文本文件?

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(); 

尝试从这篇文章中的这个例子 – 演示redirect控制台输出到一个文件

 static public void Main () { FileStream ostrm; StreamWriter writer; TextWriter oldOut = Console.Out; try { ostrm = new FileStream ("./Redirect.txt", FileMode.OpenOrCreate, FileAccess.Write); writer = new StreamWriter (ostrm); } catch (Exception e) { Console.WriteLine ("Cannot open Redirect.txt for writing"); Console.WriteLine (e.Message); return; } Console.SetOut (writer); Console.WriteLine ("This is a line of text"); Console.WriteLine ("Everything written to Console.Write() or"); Console.WriteLine ("Console.WriteLine() will be written to a file"); Console.SetOut (oldOut); writer.Close(); ostrm.Close(); Console.WriteLine ("Done"); } 

尝试如果这个工程:

 FileStream filestream = new FileStream("out.txt", FileMode.Create); var streamwriter = new StreamWriter(filestream); streamwriter.AutoFlush = true; Console.SetOut(streamwriter); Console.SetError(streamwriter); 

对于这个问题:

如何将Console.Writeline输出保存到文本文件?

我会像其他人所说的那样使用Console.SetOut


但是,它看起来更像是跟踪你的程序stream程。 我会考虑使用DebugTrace来跟踪程序状态。

它的工作方式与控制台类似,只不过您可以更好地控制input,例如WriteLineIf

Debug将只在debugging模式下运行,其中Trace将在debugging模式或释放模式下运行。

它们都允许监听器,如输出文件或控制台。

 TextWriterTraceListener tr1 = new TextWriterTraceListener(System.Console.Out); Debug.Listeners.Add(tr1); TextWriterTraceListener tr2 = new TextWriterTraceListener(System.IO.File.CreateText("Output.txt")); Debug.Listeners.Add(tr2); 

http://support.microsoft.com/kb/815788

你想写代码,或者只是使用命令行function'命令redirect',如下所示:

app.exe >> output.txt

如下所示: http : //discomoose.org/2006/05/01/output-redirection-to-a-file-from-the-windows-command-line/ (归档于archive.org )

编辑:链接死了,这是另一个例子: http : //pcsupport.about.com/od/commandlinereference/a/redirect-command-output-to-file.htm

使用Console.SetOutredirect到TextWriter如下所述: http : //msdn.microsoft.com/en-us/library/system.console.setout.aspx

在app.config中仅使用configuration:

  <system.diagnostics> <trace autoflush="true" indentsize="4"> <listeners> <add name="consoleListener" type="System.Diagnostics.ConsoleTraceListener"/> <!-- <add name="logListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="TextWriterOutput.log" /> <add name="EventLogListener" type="System.Diagnostics.EventLogTraceListener" initializeData="MyEventLog"/> --> <!-- Remove the Default listener to avoid duplicate messages being sent to the debugger for display --> <remove name="Default" /> </listeners> </trace> </system.diagnostics> 

对于testing,您可以在运行程序之前使用DebugView ,然后我们可以轻松查看所有日志消息。

参考文献:
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到控制台
问题使用跟踪侦听器将debugging输出redirect到文件
https://ukadcdiagnostics.codeplex.com/
http://geekswithblogs.net/theunstablemind/archive/2009/09/09/adventures-in-system.diagnostics.aspx

创build一个类logging器(代码如下),用Logger.OutreplaceConsole.WriteLine。 在最后写入一个文件的string日志

 public static class Logger { public static StringBuilder LogString = new StringBuilder(); public static void Out(string str) { Console.WriteLine(str); LogString.Append(str).Append(Environment.NewLine); } }