Cách lưu Bảng điều khiển. Đầu ra WriteLine thành tệp văn bản


98

Tôi có một chương trình xuất ra nhiều kết quả khác nhau trên bảng điều khiển dòng lệnh.

Làm cách nào để lưu kết quả đầu ra vào tệp văn bản bằng một StreamReaderhoặc các kỹ thuật khác?

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âu trả lời:


150

Hãy thử ví dụ này từ bài viết này - Thể hiện chuyển hướng đầu ra của Bảng điều khiển đến một tệp

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
đã thêm cái này vào mẫu bảng điều khiển thử nghiệm tiêu chuẩn của tôi.
Valamas

Có thể chỉ sử dụng app.config, không theo chương trình, section system.diagnostics không? Bất kỳ mẫu?
Kiquenet

Há chẳng phải tốt hơn để sử dụng sử dụng ?
John

Tôi đã viết một lớp tiện ích nhỏ ( DebugLogger) mà tôi đưa vào tất cả các bài kiểm tra đơn vị của mình và khởi tạo dưới dạng một private static readonly. Trong [ClassCleanup]phương pháp tôi thực hiệnDispose()
IAbstract

16
Tôi tự hỏi liệu bạn có thể hiển thị kết quả đầu ra trên bảng điều khiển lưu nó vào tệp cùng một lúc hay không.
John Alexiou

54

Hãy thử nếu điều này hoạt động:

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

3
Câu trả lời tuyệt vời - lưu ý rằng điều này chuyển hướng đầu ra bảng điều khiển, vì vậy bạn chỉ nhận được nhật ký. Ngoài ra, bạn có thể sử dụng FileMode.Append để giữ các bản ghi trước đó.
Dunc

3
Console.SetOut(System.IO.TextWriter.Null)nếu bạn muốn tắt đăng nhập.
tổng kiểm tra

22

Đối với câu hỏi:

Làm thế nào để lưu các đầu ra Console.Writeline vào tệp văn bản?

Tôi sẽ sử dụng Console.SetOutnhư những người khác đã đề cập.


Tuy nhiên, có vẻ như bạn đang theo dõi luồng chương trình của mình. Tôi sẽ cân nhắc sử dụng Debughoặc Traceđể theo dõi trạng thái chương trình.

Nó hoạt động tương tự như bảng điều khiển ngoại trừ bạn có nhiều quyền kiểm soát hơn đối với đầu vào của mình chẳng hạn như WriteLineIf.

Debugsẽ chỉ hoạt động khi ở chế độ gỡ lỗi, nơi Tracesẽ hoạt động ở cả chế độ gỡ lỗi hoặc phát hành.

Cả hai đều cho phép người nghe như tệp đầu ra hoặc bảng điều khiển.

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

bạn có muốn viết mã cho điều đó hay chỉ sử dụng tính năng dòng lệnh 'chuyển hướng lệnh' như sau:

app.exe >> output.txt

như được minh họa ở đây: http://discomoose.org/2006/05/01/output-redirection-to-a-file-from-the-windows-command-line/ (Lưu trữ tại archive.org )

CHỈNH SỬA: liên kết đã chết, đây là một ví dụ khác: http://pcsupport.about.com/od/commandlinereference/a/redirect-command-output-to-file.htm


Giải pháp này tốt hơn cho tôi vì tôi thấy rằng đầu ra của tôi đã bị cắt bớt khi sử dụng giải pháp TextWriter. Nếu bạn muốn có một liên kết mới, hãy tìm kiếm Command Redirection, ví dụ. technet.microsoft.com/en-us/library/bb490982.aspx
mafue

Sử dụng tính năng chuyển hướng trong ví dụ dơi / file cmd gây sản lượng được chuyển đổi sang bảng mã 850.
galmok

5

Tạo một Logger lớp (mã bên dưới), thay thế Console.WriteLine bằng Logger.Out. Cuối ghi vào một tệp, chuỗi Nhật ký

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

Điều này thật đúng với gì mà tôi đã tìm kiếm.
Jhollman


2

Dựa trên câu trả lời của WhoIsNinja:

Mã này sẽ xuất cả vào Bảng điều khiển và thành một chuỗi Nhật ký có thể được lưu vào một tệp, bằng cách nối các dòng vào nó hoặc bằng cách ghi đè lên nó.

Tên mặc định cho tệp nhật ký là 'Log.txt' và được lưu trong đường dẫn Ứng dụng.

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

Sau đó, bạn có thể sử dụng nó như thế này:

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
Trong khi rất lớn, bạn sẽ mất các chức năng định dạng được xây dựng vào Console.WriteConsole.WriteLine
Cole Johnson

1

Chỉ sử dụng cấu hình trong app.config của bạn:

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

Để thử nghiệm, bạn có thể sử dụng DebugView trước khi chạy chương trình, sau đó chúng ta có thể dễ dàng xem tất cả các thông báo nhật ký.

Tài liệu tham khảo:
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
Chuyển hướng đầu ra theo dõi sang bảng điều khiển Sự cố
chuyển hướng đầu ra gỡ lỗi thành tệp bằng trình nghe theo dõi
https://ukadcdiagnostics.codeplex.com/
http://geekswithblogs.net/theunstablemind/archive/2009/09/09/adventures-in-system.diagnostics .aspx


Điều này sẽ không hoạt động với Trace.WriteLine chứ không phải Console.WriteLine?
Tomer Cagan

@TomerCagan Có thể sử dụng ConsoleTraceListener và Console.SetOut. Thông tin thêm trong tài liệu tham khảo.
Kiquenet
Khi sử dụng trang web của chúng tôi, bạn xác nhận rằng bạn đã đọc và hiểu Chính sách cookieChính sách bảo mật của chúng tôi.
Licensed under cc by-sa 3.0 with attribution required.