我有一个程序,可以将各种结果输出到命令行控制台上。
如何使用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();
发布于 2010-12-17 21:12:08
尝试本文中的这个例子-- 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");
}
发布于 2010-12-17 21:12:28
如果此方法有效,请尝试:
FileStream filestream = new FileStream("out.txt", FileMode.Create);
var streamwriter = new StreamWriter(filestream);
streamwriter.AutoFlush = true;
Console.SetOut(streamwriter);
Console.SetError(streamwriter);
发布于 2013-03-19 10:17:53
创建一个类记录器(代码如下),用Logger.Out替换Console.WriteLine。最后,将字符串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);
}
}
https://stackoverflow.com/questions/4470700
复制相似问题