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


98

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

如何使用a 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();

Answers:


150

请尝试本文中的此示例- 演示将控制台输出重定向到文件

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

1
将此添加到我的标准测试控制台模板中。
Valamas 2014年

是否只能使用app.config而不以编程方式使用system.diagnostics部分?有样品吗?
Kiquenet

这难道不是最好使用使用
约翰

我编写了一个小的实用程序类(DebugLogger),将其包含在所有单元测试中并初始化为private static readonly。在[ClassCleanup]我执行的方法中Dispose()
IAbstract

16
我想知道您是否可以在控制台上显示输出并将其同时保存到文件中。
John Alexiou

54

尝试这样做是否可行:

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

3
很好的答案-请注意,这将重定向控制台输出,因此您仅能记录日志。另外,您可以使用FileMode.Append保留以前的日志。
Dunc

3
Console.SetOut(System.IO.TextWriter.Null)如果要关闭登录。
校验和

22

对于这个问题:

如何将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


14

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

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/zh-CN/library/bb490982.aspx
mafue 2014年

使用在例如蝙蝠/ CMD文件重定向特性导致的输出被转换为代码页850
galmok

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

这正是我在寻找的东西。
Jhollman '19


2

根据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.

1
虽然伟大,你就失去了格式化的功能内置到Console.WriteConsole.WriteLine
科尔约翰逊

1

仅在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
将跟踪输出重定向到控制台
使用跟踪侦听器将调试输出重定向到文件时出现问题
https://ukadcdiagnostics.codeplex.com/
http://geekswithblogs.net/theunstablemind/archive/2009/09/09/adventures-in-system.diagnostics .aspx


这不适用于Trace.WriteLine而不适用于Console.WriteLine吗?
Tomer Cagan 2014年

@TomerCagan也许使用ConsoleTraceListener和Console.SetOut。参考中的更多信息。
Kiquenet 2014年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.