C# d覆盖无效处置(bool处置) { foreach(System.IO.TextWriter thisWriter在此.m_Writer中) { thisWriter.Dispose(); } } 公共异步覆盖System.Threading.Tasks.
d覆盖无效处置(bool处置) { foreach(System.IO.TextWriter thisWriter在此.m_Writer中) { thisWriter.Dispose(); } } 公共异步覆盖System.Threading.Tasks.ValueTask DisposeAsync() { foreach(System.IO.TextWriter thisWriter在此.m_Writer中) { 等待本文作者。DisposeAsync(); } 等待System.Threading.Tasks.Task.CompletedTask; } 公共覆盖无效关闭() { foreach(System.IO.TextWriter thisWriter在此.m_Writer中) { thisWriter.Close(); } }//结束子关闭 }//结束类MultiTextWriter 公共类控制台输出多路复用器 :System.IDisposable { 受保护的System.IO.TextWriter m_oldOut; 受保护的System.IO.FileStream m_logStream; 受保护的System.IO.StreamWriter m_logWriter; 受保护的MultiTextWriter m_多路复用器; 公共控制台输出多路复用器() { this.m_oldOut=System.Console.Out; 尝试 { this.m_logStream=new System.IO.FileStream(“./Redirect.txt”,System.IO.FileMode.OpenOrCreate,System.IO.FileAccess.Write); this.m_logWriter=new System.IO.StreamWriter(this.m_logStream); this.m_multiPlexer=新的MultiTextWriter(this.m_oldOut.Encoding,this.m_oldOut,this.m_logWriter); 系统控制台放线(此.m_多路复用器); } 捕获(System.e例外) { System.Console.WriteLine(“无法打开Redirect.txt进行写入”); 系统控制台写入线(e.Message); 返回; } }//结束构造函数 void System.IDisposable.Dispose() { 系统控制台放线(本m_oldOut); if(此.m_多路复用器!=null) { 这个.m_multiPlexer.Flush(); if(this.m_logStream!=null) 这个.m_logStream.Flush(); 此.m_多路复用器.Close(); } if(this.m_logStream!=null) 这个.m_logStream.Close(); }//结束子处理 }//端类控制台输出多路复用器C# d覆盖无效处置(bool处置) { foreach(System.IO.TextWriter thisWriter在此.m_Writer中) { thisWriter.Dispose(); } } 公共异步覆盖System.Threading.Tasks.,c#,C#,d覆盖无效处置(bool处置) { foreach(System.IO.TextWriter thisWriter在此.m_Writer中) { thisWriter.Dispose(); } } 公共异步覆盖System.Threading.Tasks.ValueTask DisposeAsync() { foreach(System.IO.TextWriter thisWriter在此.m_Writer中) { 等待本文作者。DisposeAsync(); } 等待System.Thread
Great answer-注意,这会重定向控制台输出,因此您只能获得日志记录。此外,您可以使用FileMode.Append来保留以前的日志。
Console.SetOut(System.IO.TextWriter.Null)
如果您想关闭日志,请将其添加到我的标准测试控制台模板中。是否可以仅使用app.config,而不以编程方式使用System.diagnostics部分?任何示例?使用不是更好吗?我编写了一个小实用程序类(DebugLogger
),我将其包含在所有单元测试中,并初始化为私有静态只读。在[ClassCleanup]
方法中,我执行Dispose()
我想知道您是否可以在控制台上显示输出,并同时将其保存到文件中。此解决方案对我来说更好,因为我发现我的输出被使用TextWriter解决方案截断。如果您想要一个新链接,请搜索命令重定向,例如,在bat/cmd文件中使用重定向功能会导致输出转换为代码页850。这不适用于Trace.WriteLine而不是Console.WriteLine吗?@TomerCagan可能使用ConsoleTraceListener和Console.SetOut。参考资料中有更多信息。这可能是我一直在寻找的副本。虽然很好,但您丢失了控制台中内置的格式化功能。Write
和控制台。WriteLine
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();
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");
}
FileStream filestream = new FileStream("out.txt", FileMode.Create);
var streamwriter = new StreamWriter(filestream);
streamwriter.AutoFlush = true;
Console.SetOut(streamwriter);
Console.SetError(streamwriter);
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);
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);
}
}
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.
public class Program
{
public static async System.Threading.Tasks.Task Main(string[] args)
{
using (ConsoleOutputMultiplexer co = new ConsoleOutputMultiplexer())
{
// Do something here
System.Console.WriteLine("Hello Logfile and Console 1 !");
System.Console.WriteLine("Hello Logfile and Console 2 !");
System.Console.WriteLine("Hello Logfile and Console 3 !");
} // End Using co
System.Console.WriteLine(" --- Press any key to continue --- ");
System.Console.ReadKey();
await System.Threading.Tasks.Task.CompletedTask;
} // End Task Main
}
public class MultiTextWriter
: System.IO.TextWriter
{
protected System.Text.Encoding m_encoding;
protected System.Collections.Generic.IEnumerable<System.IO.TextWriter> m_writers;
public override System.Text.Encoding Encoding => this.m_encoding;
public override System.IFormatProvider FormatProvider
{
get
{
return base.FormatProvider;
}
}
public MultiTextWriter(System.Collections.Generic.IEnumerable<System.IO.TextWriter> textWriters, System.Text.Encoding encoding)
{
this.m_writers = textWriters;
this.m_encoding = encoding;
}
public MultiTextWriter(System.Collections.Generic.IEnumerable<System.IO.TextWriter> textWriters)
: this(textWriters, textWriters.GetEnumerator().Current.Encoding)
{ }
public MultiTextWriter(System.Text.Encoding enc, params System.IO.TextWriter[] textWriters)
: this((System.Collections.Generic.IEnumerable<System.IO.TextWriter>)textWriters, enc)
{ }
public MultiTextWriter(params System.IO.TextWriter[] textWriters)
: this((System.Collections.Generic.IEnumerable<System.IO.TextWriter>)textWriters)
{ }
public override void Flush()
{
foreach (System.IO.TextWriter thisWriter in this.m_writers)
{
thisWriter.Flush();
}
}
public async override System.Threading.Tasks.Task FlushAsync()
{
foreach (System.IO.TextWriter thisWriter in this.m_writers)
{
await thisWriter.FlushAsync();
}
await System.Threading.Tasks.Task.CompletedTask;
}
public override void Write(char[] buffer, int index, int count)
{
foreach (System.IO.TextWriter thisWriter in this.m_writers)
{
thisWriter.Write(buffer, index, count);
}
}
public override void Write(System.ReadOnlySpan<char> buffer)
{
foreach (System.IO.TextWriter thisWriter in this.m_writers)
{
thisWriter.Write(buffer);
}
}
public async override System.Threading.Tasks.Task WriteAsync(char[] buffer, int index, int count)
{
foreach (System.IO.TextWriter thisWriter in this.m_writers)
{
await thisWriter.WriteAsync(buffer, index, count);
}
await System.Threading.Tasks.Task.CompletedTask;
}
public async override System.Threading.Tasks.Task WriteAsync(System.ReadOnlyMemory<char> buffer, System.Threading.CancellationToken cancellationToken = default)
{
foreach (System.IO.TextWriter thisWriter in this.m_writers)
{
await thisWriter.WriteAsync(buffer, cancellationToken);
}
await System.Threading.Tasks.Task.CompletedTask;
}
protected override void Dispose(bool disposing)
{
foreach (System.IO.TextWriter thisWriter in this.m_writers)
{
thisWriter.Dispose();
}
}
public async override System.Threading.Tasks.ValueTask DisposeAsync()
{
foreach (System.IO.TextWriter thisWriter in this.m_writers)
{
await thisWriter.DisposeAsync();
}
await System.Threading.Tasks.Task.CompletedTask;
}
public override void Close()
{
foreach (System.IO.TextWriter thisWriter in this.m_writers)
{
thisWriter.Close();
}
} // End Sub Close
} // End Class MultiTextWriter
public class ConsoleOutputMultiplexer
: System.IDisposable
{
protected System.IO.TextWriter m_oldOut;
protected System.IO.FileStream m_logStream;
protected System.IO.StreamWriter m_logWriter;
protected MultiTextWriter m_multiPlexer;
public ConsoleOutputMultiplexer()
{
this.m_oldOut = System.Console.Out;
try
{
this.m_logStream = new System.IO.FileStream("./Redirect.txt", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
this.m_logWriter = new System.IO.StreamWriter(this.m_logStream);
this.m_multiPlexer = new MultiTextWriter(this.m_oldOut.Encoding, this.m_oldOut, this.m_logWriter);
System.Console.SetOut(this.m_multiPlexer);
}
catch (System.Exception e)
{
System.Console.WriteLine("Cannot open Redirect.txt for writing");
System.Console.WriteLine(e.Message);
return;
}
} // End Constructor
void System.IDisposable.Dispose()
{
System.Console.SetOut(this.m_oldOut);
if (this.m_multiPlexer != null)
{
this.m_multiPlexer.Flush();
if (this.m_logStream != null)
this.m_logStream.Flush();
this.m_multiPlexer.Close();
}
if(this.m_logStream != null)
this.m_logStream.Close();
} // End Sub Dispose
} // End Class ConsoleOutputMultiplexer