วิธีบันทึก 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();

คำตอบ:


151

ลองใช้ตัวอย่างนี้จากบทความนี้ - แสดงให้เห็นถึงการเปลี่ยนเส้นทางเอาต์พุตคอนโซลไปยังไฟล์

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

เป็นไปได้หรือไม่โดยใช้ app.config ไม่ใช่โดยใช้โปรแกรมส่วน system.diagnostics ตัวอย่างใด ๆ
Kiquenet

มันไม่ได้ดีกว่าการใช้ใช้ ?
John

ฉันเขียนคลาสยูทิลิตี้ขนาดเล็ก ( DebugLogger) ที่ฉันรวมไว้ในการทดสอบหน่วยทั้งหมดของฉันและเริ่มต้นเป็นไฟล์private static readonly. ใน[ClassCleanup]วิธีที่ฉันดำเนินการDispose()
IAbstract

18
ฉันสงสัยว่าคุณสามารถแสดงผลลัพธ์บนคอนโซลและบันทึกลงในไฟล์พร้อมกันได้หรือไม่
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 ได้ผนวกเพื่อเก็บบันทึกก่อนหน้านี้
Dunc

4
Console.SetOut(System.IO.TextWriter.Null)หากคุณต้องการปิดระบบ
เช็ค

22

สำหรับคำถาม:

วิธีบันทึก Console.Writeline ส่งออกไปยังไฟล์ข้อความ

ฉันจะใช้Console.SetOutตามที่คนอื่นกล่าวถึง


อย่างไรก็ตามดูเหมือนว่าคุณกำลังติดตามขั้นตอนของโปรแกรมอยู่ ฉันจะพิจารณาใช้DebugหรือTraceเพื่อติดตามสถานะของโปรแกรม

ทำงานคล้ายกับคอนโซลยกเว้นว่าคุณสามารถควบคุมอินพุตของคุณได้มากขึ้นเช่น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 หากคุณต้องการลิงค์ใหม่ให้ค้นหา Command Redirection เช่น technet.microsoft.com/en-us/library/bb490982.aspx
mafue

การใช้คุณลักษณะการเปลี่ยนเส้นทางในไฟล์เช่น bat / cmd ทำให้เอาต์พุตถูกแปลงเป็น codepage 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


2

จากคำตอบของ WhoIsNinja:

รหัสนี้จะส่งออกทั้งในคอนโซลและในสตริงบันทึกที่สามารถบันทึกลงในไฟล์ไม่ว่าจะโดยการต่อท้ายบรรทัดหรือโดยการเขียนทับ

ชื่อดีฟอลต์สำหรับล็อกไฟล์คือ 'Log.txt' และถูกบันทึกภายใต้ Application path

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.WriteและConsole.WriteLine
Cole Johnson

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
เปลี่ยนเส้นทางเอาต์พุต Trace ไปยัง Console
Problem ในการเปลี่ยนทิศทางเอาต์พุต debug ไปยังไฟล์โดยใช้ trace listener
https://ukadcdiagnostics.codeplex.com/
http://geekswithblogs.net/theunstablemind/archive/2009/09/09/adventures-in-system.diagnostics .aspx


สิ่งนี้จะใช้ไม่ได้กับ Trace.WriteLine และไม่ใช่ Console.WriteLine?
Tomer Cagan

@TomerCagan อาจจะใช้ ConsoleTraceListener และ Console.SetOut ข้อมูลเพิ่มเติมในการอ้างอิง
Kiquenet
โดยการใช้ไซต์ของเรา หมายความว่าคุณได้อ่านและทำความเข้าใจนโยบายคุกกี้และนโยบายความเป็นส่วนตัวของเราแล้ว
Licensed under cc by-sa 3.0 with attribution required.