首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何将Console.WriteLine输出保存到文本文件

如何将Console.WriteLine输出保存到文本文件
EN

Stack Overflow用户
提问于 2010-12-17 21:06:43
回答 7查看 224.7K关注 0票数 101

我有一个程序,可以将各种结果输出到命令行控制台上。

如何使用StreamReader或其他技术将输出保存到文本文件?

代码语言:javascript
复制
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();
EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2010-12-17 21:12:08

尝试本文中的这个例子-- Demonstrates redirecting the Console output to a file

代码语言:javascript
复制
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");
}
票数 160
EN

Stack Overflow用户

发布于 2010-12-17 21:12:28

如果此方法有效,请尝试:

代码语言:javascript
复制
FileStream filestream = new FileStream("out.txt", FileMode.Create);
var streamwriter = new StreamWriter(filestream);
streamwriter.AutoFlush = true;
Console.SetOut(streamwriter);
Console.SetError(streamwriter);
票数 58
EN

Stack Overflow用户

发布于 2013-03-19 10:17:53

创建一个类记录器(代码如下),用Logger.Out替换Console.WriteLine。最后,将字符串Log写入文件

代码语言:javascript
复制
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);
     }
 }
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4470700

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档