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 2014

それは使用しない方がよい使用して
ジョン

DebugLoggerすべての単体テストに含め、として初期化する小さなユーティリティクラス()を書きましたprivate static readonly。では[ClassCleanup]この方法私は実行Dispose()
IAbstract

16
あなたがコンソールに出力を表示することができているのだろうか、それは同時に、ファイルに保存しています。
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を使用して以前のログを保持することもできます。
2013

3
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ソリューションを使用すると出力が切り捨てられることがわかったため、このソリューションの方が適しています。新しいリンクが必要な場合は、コマンドリダイレクトを検索してください。technet.microsoft.com/en-us/library/bb490982.aspx
mafue

出力を例えばバット/ 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


これは、Trace.WriteLineでは機能し、Console.WriteLineでは機能しませんか?
Tomer Cagan 2014年

@TomerCagan ConsoleTraceListenerとConsole.SetOutを使用している可能性があります。参照の詳細情報。
Kiquenet 2014年
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.