Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
586 views
in Technique[技术] by (71.8m points)

c# - How to Save Console.WriteLine Output to Text File

I have a program which outputs various results onto a command line console.

How do I save the output to a text file using a StreamReader or other techniques?

System.Collections.Generic.IEnumerable<String> lines = File.ReadAllLines(@"C:Test
tfs8.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();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this example from this article - Demonstrates redirecting the Console output to a file

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...