在C#控制台应用程序中,是否有一种智能方法可以将控制台输出镜像到文本文件中?
目前我只是将相同的字符串传递给两个Console.WriteLine和InstanceOfStreamWriter.WriteLine一个日志方法.
假设我正在使用VB.Net中的一个小批量处理控制台应用程序.我希望能够像这样构建应用程序:
Sub WorkerMethod()
'Do some work
Trace.WriteLine("Work progress")
'Do more work
Trace.WriteLine("Another progress update")
'...
End Sub
Sub Main()
'Do any setup, like confirm the user wants to continue or whatever
WorkerMethod()
End Sub
Run Code Online (Sandbox Code Playgroud)
请注意,我正在使用Trace而不是Console我的输出.这是因为可以从其他地方调用worker方法,或甚至生活在不同的程序集中,并且我希望能够为其附加不同的跟踪侦听器.那么如何将控制台连接到跟踪?
我已经可以通过定义一个简单的类(如下所示)并在Trace的侦听器集合中添加一个实例来实现它,但我想知道是否有更多接受或内置的方法来完成此任务:
Public Class ConsoleTrace
Inherits Diagnostics.TraceListener
Public Overloads Overrides Sub Write(ByVal message As String)
Console.Write(message)
End Sub
Public Overloads Overrides Sub WriteLine(ByVal message As String)
Console.WriteLine(message)
End Sub
End Class
Run Code Online (Sandbox Code Playgroud) 我创建了一个调试监听器,使用以下代码将Debug/Console窗口的输出重定向到一个文件(带有一个调用堆栈):
void SomeMethod()
{
// Create a file for output .txt.
Stream debugFile = File.Create(fileName);
// create TextWriterTraceListener named "file"
TextWriterTraceListener debugWriter = new TextWriterTraceListener(debugFile, "file");
// add to debug listeners
Debug.Listeners.Add(debugWriter);
// set callstack to be shown
Debug.Listeners["file"].TraceOutputOptions |= TraceOptions.Callstack;
// set auto-flush
Debug.AutoFlush = true;
}
Run Code Online (Sandbox Code Playgroud)
但输出不会重定向到我指定的文件,它总是为空.
我从我的主窗体中的构造函数中调用它.我是从问题中调用它的地方吗?
我在这里尝试实现的是将调试输出窗口中的异常放在带有调用堆栈的文件中,以便我可以找到它们并更正它们.
更新:经过一些研究后,我得出结论,TraceListener在Debug Listeners集合中添加一个新的不会重定向调试/控制台的输出.它实际上只是回应Write,WriteLine等方法一样默认的监听器.问题仍然存在:如何捕获Debug/Console窗口的输出以及如何获取出现在那里的异常的堆栈跟踪?
有人有主意吗?
我在互联网上搜索了许多将控制台应用程序输出屏幕存储在.txt文件中.我得到了解决方案,但我没有得到预期的结果.问题是未在控制台屏幕中显示的文本存储在记事本文件中.但控制台屏幕中显示的文本未存储在记事本文件中.
例如,
using System;
using System.IO;
static void Main(string[] args)
{
Console.WriteLine("Text which is displayed in the the console output screen ");
FileStream filestream = new FileStream("notepad.txt", FileMode.Create);
var streamwriter = new StreamWriter(filestream);
streamwriter.AutoFlush = true;
Console.SetOut(streamwriter);
Console.SetError(streamwriter);
Console.WriteLine("Text which is not displayed in the console output screen but it store in the the .txt file");
Console.ReadKey();
}
Run Code Online (Sandbox Code Playgroud)
在上面的示例中,
该行Console.WriteLine("Text which is displayed in the the console output screen ");仅显示在控制台屏幕中,但未存储在记事本文件中
但该行Console.WriteLine("Text which is not displayed …