Console.WriteLine 출력을 텍스트 파일에 저장하는 방법


98

명령 줄 콘솔에 다양한 결과를 출력하는 프로그램이 있습니다.

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

답변:


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

그것은 사용하지 않는 것이 좋다 사용 ?
John

나는 작은 유틸리티 클래스를 (쓴 DebugLogger내 단위 테스트의 모든에 포함하고로 초기화 할 것을) private static readonly. [ClassCleanup]내가 실행 하는 방법에서Dispose()
IAbstract

17
콘솔에 출력을 표시 할 수 있는지 궁금해 하고 동시에 파일에 저장을합니다.
John Alexiou 2017 년

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를 사용하여 이전 로그를 유지할 수 있습니다.
덩크

3
Console.SetOut(System.IO.TextWriter.Null)로그 오프를 원하는 경우.
검사

22

질문 :

Console.Writeline 출력을 텍스트 파일에 저장하는 방법은 무엇입니까?

나는 Console.SetOut다른 사람들이 언급했듯이 사용합니다.


그러나 프로그램 흐름을 추적하는 것처럼 보입니다. 프로그램 상태를 추적 Debug하거나 사용하는 것을 고려할 것 Trace입니다.

와 같은 입력을 더 많이 제어 할 수 있다는 점을 제외하면 콘솔과 비슷하게 작동합니다 WriteLineIf.

DebugTrace디버그 또는 릴리스 모드 모두에서 작동하는 디버그 모드에서만 작동 합니다.

둘 다 출력 파일 또는 콘솔과 같은 리스너를 허용합니다.

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/en-us/library/bb490982.aspx
mafue 2014-06-10

예를 들어 bat / 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


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


이것은 Console.WriteLine이 아닌 Trace.WriteLine에서 작동하지 않습니까?
Tomer Cagan 2014 년

@TomerCagan 아마도 ConsoleTraceListener 및 Console.SetOut을 사용할 수 있습니다. 참고 문헌에서 더 많은 정보.
Kiquenet 2014 년
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.