我在互联网上搜索了很多以将控制台应用程序输出屏幕存储在 .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();
}
在上面的例子中
Console.WriteLine("Text which is displayed in the console output screen");
仅显示在控制台屏幕中,但未存储在notepad 文件中
但是行 Console.WriteLine("Text which is not displayed in the console output screen but it store in the .txt file");
没有显示在控制台应用程序屏幕中,而是它存储在记事本文件中。
我需要存储控制台屏幕上显示的所有内容,甚至用户提供的详细信息。
我该怎么做?
作为初学者,我希望答案很简单。
提前致谢!
最佳答案
您只能将一个输出流分配给控制台。因此,您将需要一个同时执行这两种操作的流,即写入屏幕和文件。
你总是可以像这样得到控制台的标准输出流:
Stream consoleOutput = Console.GetStandardOutput();
如果你想使用多个输出,你必须创建一个新的流类,将数据分发到多个流。为此,您必须覆盖 Stream
类(不是完整实现,您还必须实现 Stream
的所有其他抽象成员):
public class MultiStream : Stream {
private readonly Stream[] m_children;
public MultiStream(params Stream[] children) {
m_children = children;
}
public override Write(byte[] buffer, int offset, int count) {
foreach(Stream child in m_children) {
child.Write(buffer, offset, count);
}
}
//...
}
现在您可以使用 MultiStream
将输出路由到多个流:
FileStream filestream = new FileStream("notepad.txt", FileMode.Create);
MultiStream outStream = new MultiStream(filestream, Console.GetStandardOutput());
var streamwriter = new StreamWriter(outStream);
如果您可以替换 Console.WriteLine
,您可以使用更简单的方法(假设您的 streamwriter
变量是可访问的):
public void WriteLineToScreenAndFile(string text) {
Console.WriteLine(text);
streamwriter.WriteLine(text);
}
您可以用对该方法的调用替换对 Console.WriteLine 的所有调用。
关于c# - 将控制台应用程序屏幕保存在 .txt 文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40803567/