【问题标题】:How to Save Console.WriteLine Output to Text File如何将 Console.WriteLine 输出保存到文本文件
【发布时间】:2010-12-17 13:06:43
【问题描述】:

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

如何使用StreamReader 或其他技术将输出保存到文本文件?

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

【问题讨论】:

标签: c#


【解决方案1】:

试试这篇文章中的这个例子 - Demonstrates redirecting the Console output to a file

using System;
using System.IO;

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");
}

【讨论】:

  • 将此添加到我的标准测试控制台模板中。
  • 是否只能使用 app.config 而不是以编程方式使用 system.diagnostics 部分?有样品吗?
  • 使用using不是更好吗?
  • 我编写了一个小型实用程序类 (DebugLogger),我将其包含在所有单元测试中并初始化为 private static readonly。在[ClassCleanup] 方法中我执行Dispose()
  • 我想知道您是否可以在控制台上显示输出将其同时保存到文件中。
【解决方案2】:

试试这是否可行:

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

【讨论】:

  • 很好的答案 - 请注意此 redirects 控制台输出,因此您只能获得日志记录。此外,您可以使用 FileMode.Append 保留以前的日志。
  • Console.SetOut(System.IO.TextWriter.Null) 如果你想关闭注销。
【解决方案3】:

关于问题:

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

我会像其他人提到的那样使用Console.SetOut


但是,您似乎在跟踪您的程序流程。我会考虑使用DebugTrace 来跟踪程序状态。

它的工作原理与控制台类似,但您可以更好地控制输入,例如 WriteLineIf

Debug 只会在调试模式下运行,而Trace 将在调试或发布模式下运行。

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

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

【讨论】:

    【解决方案4】:

    您想为此编写代码还是只使用命令行功能“命令重定向”,如下所示:

    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

    【讨论】:

    • 这个解决方案对我来说更好,因为我发现我的输出被使用 TextWriter 解决方案截断了。如果您想要一个新链接,请搜索命令重定向,例如。 technet.microsoft.com/en-us/library/bb490982.aspx
    • 使用重定向功能,例如bat/cmd 文件导致输出转换为代码页 850。
    【解决方案5】:

    创建一个 Logger 类(代码如下),将 Console.WriteLine 替换为 Logger.Out。 最后将字符串 Log 写入文件

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

    【讨论】:

    • 这正是我想要的。
    • 不能对直接打印到控制台的已编译库执行此操作
    【解决方案6】:

    根据 WhoIsNinja 的回答:

    此代码将输出到控制台和日志字符串中,该字符串可以通过向其附加行或覆盖它来保存到文件中。

    日志文件的默认名称为“Log.txt”并保存在应用程序路径下。

    public static class Logger
    {
        public static StringBuilder LogString = new StringBuilder();
        public static void WriteLine(string str)
        {
            Console.WriteLine(str);
            LogString.Append(str).Append(Environment.NewLine);
        }
        public static void Write(string str)
        {
            Console.Write(str);
            LogString.Append(str);
    
        }
        public static void SaveLog(bool Append = false, string Path = "./Log.txt")
        {
            if (LogString != null && LogString.Length > 0)
            {
                if (Append)
                {
                    using (StreamWriter file = System.IO.File.AppendText(Path))
                    {
                        file.Write(LogString.ToString());
                        file.Close();
                        file.Dispose();
                    }
                }
                else
                {
                    using (System.IO.StreamWriter file = new System.IO.StreamWriter(Path))
                    {
                        file.Write(LogString.ToString());
                        file.Close();
                        file.Dispose();
                    }
                }               
            }
        }
    }
    

    那么你可以这样使用它:

    Logger.WriteLine("==========================================================");
    Logger.Write("Loading 'AttendPunch'".PadRight(35, '.'));
    Logger.WriteLine("OK.");
    
    Logger.SaveLog(true); //<- default 'false', 'true' Append the log to an existing file.
    

    【讨论】:

    • 虽然很棒,但您会失去 Console.WriteConsole.WriteLine 中内置的格式化功能
    【解决方案7】:

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

    【讨论】:

      【解决方案8】:

      只在你的 app.config 中使用配置:

          <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>
      

      为了测试,你可以在运行程序之前使用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 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

      【讨论】:

      • 这不适用于 Trace.WriteLine 而不是 Console.WriteLine?
      • @TomerCagan 也许使用 ConsoleTraceListener 和 Console.SetOut。参考资料中的更多信息。
      【解决方案9】:

      死灵术。
      我通常只创建一个类,我可以将它包裹在 IDisposable 中。
      所以我可以在不修改其余代码的情况下将控制台输出记录到文件中。
      这样,我在控制台和文本文件中都有输出供以后参考。

      public class Program
      {
      
          public static async System.Threading.Tasks.Task Main(string[] args)
          {
              using (ConsoleOutputMultiplexer co = new ConsoleOutputMultiplexer())
              {
                  // Do something here
                  System.Console.WriteLine("Hello Logfile and Console 1 !");
                  System.Console.WriteLine("Hello Logfile and Console 2 !");
                  System.Console.WriteLine("Hello Logfile and Console 3 !");
              } // End Using co 
      
      
              System.Console.WriteLine(" --- Press any key to continue --- ");
              System.Console.ReadKey();
      
              await System.Threading.Tasks.Task.CompletedTask;
          } // End Task Main 
      
      }
      

      public class MultiTextWriter
          : System.IO.TextWriter
      {
      
          protected System.Text.Encoding m_encoding;
          protected System.Collections.Generic.IEnumerable<System.IO.TextWriter> m_writers;
      
      
          public override System.Text.Encoding Encoding => this.m_encoding;
      
      
          public override System.IFormatProvider FormatProvider
          {
              get
              {
                  return base.FormatProvider;
              }
          }
      
      
          public MultiTextWriter(System.Collections.Generic.IEnumerable<System.IO.TextWriter> textWriters, System.Text.Encoding encoding)
          {
              this.m_writers = textWriters;
              this.m_encoding = encoding;
          }
      
      
          public MultiTextWriter(System.Collections.Generic.IEnumerable<System.IO.TextWriter> textWriters)
              : this(textWriters, textWriters.GetEnumerator().Current.Encoding)
          { }
      
      
          public MultiTextWriter(System.Text.Encoding enc, params System.IO.TextWriter[] textWriters)
              : this((System.Collections.Generic.IEnumerable<System.IO.TextWriter>)textWriters, enc)
          { }
      
      
          public MultiTextWriter(params System.IO.TextWriter[] textWriters)
              : this((System.Collections.Generic.IEnumerable<System.IO.TextWriter>)textWriters)
          { }
      
      
          public override void Flush()
          {
              foreach (System.IO.TextWriter thisWriter in this.m_writers)
              {
                  thisWriter.Flush();
              }
          }
      
          public async override System.Threading.Tasks.Task FlushAsync()
          {
              foreach (System.IO.TextWriter thisWriter in this.m_writers)
              {
                  await thisWriter.FlushAsync();
              }
      
              await System.Threading.Tasks.Task.CompletedTask;
          }
      
      
          public override void Write(char[] buffer, int index, int count)
          {
              foreach (System.IO.TextWriter thisWriter in this.m_writers)
              {
                  thisWriter.Write(buffer, index, count);
              }
          }
      
      
          public override void Write(System.ReadOnlySpan<char> buffer)
          {
              foreach (System.IO.TextWriter thisWriter in this.m_writers)
              {
                  thisWriter.Write(buffer);
              }
          }
      
      
          public async override System.Threading.Tasks.Task WriteAsync(char[] buffer, int index, int count)
          {
              foreach (System.IO.TextWriter thisWriter in this.m_writers)
              {
                  await thisWriter.WriteAsync(buffer, index, count);
              }
      
              await System.Threading.Tasks.Task.CompletedTask;
          }
      
      
          public async override System.Threading.Tasks.Task WriteAsync(System.ReadOnlyMemory<char> buffer, System.Threading.CancellationToken cancellationToken = default)
          {
              foreach (System.IO.TextWriter thisWriter in this.m_writers)
              {
                  await thisWriter.WriteAsync(buffer, cancellationToken);
              }
      
              await System.Threading.Tasks.Task.CompletedTask;
          }
      
      
          protected override void Dispose(bool disposing)
          {
              foreach (System.IO.TextWriter thisWriter in this.m_writers)
              {
                  thisWriter.Dispose();
              }
          }
      
      
          public async override System.Threading.Tasks.ValueTask DisposeAsync()
          {
              foreach (System.IO.TextWriter thisWriter in this.m_writers)
              {
                  await thisWriter.DisposeAsync();
              }
      
              await System.Threading.Tasks.Task.CompletedTask;
          }
      
          public override void Close()
          {
      
              foreach (System.IO.TextWriter thisWriter in this.m_writers)
              {
                  thisWriter.Close();
              }
              
          } // End Sub Close 
      
      
      } // End Class MultiTextWriter 
      
      
      
      public class ConsoleOutputMultiplexer
          : System.IDisposable
      {
      
          protected System.IO.TextWriter m_oldOut;
          protected System.IO.FileStream m_logStream;
          protected System.IO.StreamWriter m_logWriter;
      
          protected MultiTextWriter m_multiPlexer;
      
      
          public ConsoleOutputMultiplexer()
          {
              this.m_oldOut = System.Console.Out;
      
              try
              {
                  this.m_logStream = new System.IO.FileStream("./Redirect.txt", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
                  this.m_logWriter = new System.IO.StreamWriter(this.m_logStream);
                  this.m_multiPlexer = new MultiTextWriter(this.m_oldOut.Encoding, this.m_oldOut, this.m_logWriter);
      
                  System.Console.SetOut(this.m_multiPlexer);
              }
              catch (System.Exception e)
              {
                  System.Console.WriteLine("Cannot open Redirect.txt for writing");
                  System.Console.WriteLine(e.Message);
                  return;
              }
      
          } // End Constructor 
      
      
          void System.IDisposable.Dispose()
          {
              System.Console.SetOut(this.m_oldOut);
      
              if (this.m_multiPlexer != null)
              {
                  this.m_multiPlexer.Flush();
                  if (this.m_logStream != null)
                      this.m_logStream.Flush();
      
                  this.m_multiPlexer.Close();
              }
              
              if(this.m_logStream != null)
                  this.m_logStream.Close();
          } // End Sub Dispose 
      
      
      } // End Class ConsoleOutputMultiplexer 
      

      【讨论】:

      • 谢谢!非常好的解决方案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-13
      • 2021-10-16
      • 2014-09-21
      • 1970-01-01
      相关资源
      最近更新 更多