【问题标题】:Saving the console application screen in .txt file将控制台应用程序屏幕保存在 .txt 文件中
【发布时间】:2017-04-09 18:30:00
【问题描述】:

我在互联网上搜索了很多内容以将控制台应用程序输出屏幕存储在 .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 the console output screen "); 行仅显示在控制台屏幕中,但未存储在 记事本 文件中

但Console.WriteLine("Text which is not displayed in the console output screen but it store in the the .txt file"); 行没有显示在控制台应用程序屏幕中,而是存储在记事本文件中。

我需要存储控制台屏幕上显示的所有内容,即使用户也提供了详细信息。

我该怎么做?

由于我是初学者,我希望答案很简单。

提前致谢!

【问题讨论】:

标签: c# console-application notepad


【解决方案1】:

您只能将一个输出流分配给控制台。因此,您将需要一个既可以写入屏幕又可以写入文件的流。

你总是可以像这样得到控制台的标准输出流:

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 的调用替换为对该方法的调用。

【讨论】:

  • 不错的解决方案,不过我不确定它是否适合初学者。
  • 对不起。不过我想不出其他解决方案。
  • 我只能想到在Console.WriteLine 周围编写一个包装器,它可以同时写入文件和屏幕。你的解决方案更整洁。不过 Wrapper 的学习曲线可能比较浅。
  • 是的,我也在考虑这个问题。如果您可以控制写入控制台的代码,那效果很好。如果不这样做,则必须使用其他方式。
  • 我已更新帖子以提供更简单的解决方案。
猜你喜欢
  • 2023-02-01
  • 2020-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-08
  • 2019-01-26
  • 1970-01-01
  • 2020-08-31
相关资源
最近更新 更多